JUnit mocks, which tool should i use?

victorgp picture victorgp · Mar 24, 2011 · Viewed 19.7k times · Source

I come from the PHP testing world and i'm starting testing in Java.

I've seen several tools to mock the SUT in JUnit, like Mockito, SevenMock, ClassMock, etc.

I really appreciate any recommendation of which one should i use.

Thanks in advance!

Answer

MalsR picture MalsR · Mar 24, 2011

I've used Mockito quite a lot. http://mockito.org/ I have not used EasyMock so cant say much about it.

Using Mockito is straightforward but the classes that you intend to test should also be in a decoupled state which will make it easier to test. With mockito you are instantiating a particular class with mocks objects.

Say you got a class that you want to test, but want to mock one of its dependencies

final DepedencyToMockClass mockObject = mock(DepedencyToMockClass.class);
when(mockObject.getTestMethod()).thenReturn("Test");

Now this mockObject can now be injected when initializing your intended class.

final ClassToTest test = new ClassToTest(mockObject);

Mockito uses reflection to create these mock objects. However if you have a dependency and if it is declared final then mocking will fail.

Another useful method in Mockito is verify where you can verify certain operations in your mock objects. Have a peep at mockito. However there are limitations in mock objects, in some cases it will be hard to create mock objects perhaps external/third party code. I think it's good practise to attempt to instantiate real objects when injecting them for testing purposes, failing which Mockito helps.