Mock Objects

Mock objects are unit testing objects that can be used in place of real objects. Many people think of them as stubs which return either hard-coded information each time or the values of instance variables. Mock objects are more than just stubs, however. First, they don't require you to explicitly define a class for the mock. It uses more generic mechanisms to either simulate or auto-generate a class. Second, you program the mock from your testcase telling it what to return. You can say that the first time a method is called return this and the second time, return that.

Mock objects tend to promote interaction based testing testing versus state based testing. In state based testing, you test an object then look at it to see what changed. In interaction based testing, you configure your object under test to talk to a mock object, run the test, then ask the mock object if it received all the correct messages. My concern about interaction based testing is that you always make assumptions on what the rest of the system is doing. Those assumptions may be wrong. You are also breaking encapsulation of the object under test by knowing what messages it sends to other objects.

For me, the jury is still out on mock objects. If you use them, make sure you have other tests that check object interactions and don't just assume that the mocks correctly simulate the rest of the environment.

Download