Jump to content

Why I dislike mocks

From EggeWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Mock's are brittle and force your tests to assume an implementation of the code you are testing. Today, the unit test broke because I added this line of code:

            LOG.debug("Received Message " + responseMessage.getJMSCorrelationID());

The reported failure:

Testcase: testRequestSendsMessageAndWaitsForResponse(JmsServiceImplUnitTest):	Caused an ERROR

  Unexpected method call getJMSCorrelationID():
java.lang.AssertionError: 
  Unexpected method call getJMSCorrelationID():
	at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
	at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:45)
	at $Proxy13.getJMSCorrelationID(Unknown Source)
	at JmsServiceImpl.makeRequest(JmsServiceImpl.java:48)
	at JmsServiceImplUnitTest.testRequestSendsMessageAndWaitsForResponse(JmsServiceImplUnitTest.java:56)

The fix:

expect(sendMessage.getJMSCorrelationID()).andReturn("JMS1").anyTimes();

Sorting out problems like this seems to be a complete waste of time. My preference would be to use a stub or a fake object.