Mock objects act like stubs in the sense that you can configure how they reply if a method is called: for example, to return a list of invoices when getAllInvoices is called. However, mocks go beyond that. They save all the interactions and allow you to make assertions afterward. For example, maybe we only want the getAllInvoices method to be called once. If the method is called twice by the class under test, this is a bug, and the test should fail. At the end of our test, we can write an assertion along the lines of “verify that getAllInvoices was called just once.”

Mocking frameworks let you assert all sorts of interactions, such as “the method was never called with this specific parameter” or “the method was called twice with parameter A and once with parameter B.” Mocks are also popular in industry since they can provide insight into how classes interact.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *