JUnit mocks, which tool should i use? [closed]
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!
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.
Mockito seems to be most often used
edit:
Comparison between Mockito vs JMockit - why is Mockito voted better than JMockit?
EasyMock vs Mockito: design vs maintainability?
http://www.dahliabock.com/blog/2009/08/21/mocking-mockito-vs-easymock-example/
I've been using JMock for a while. I personally like that the resulting code is easy to read, and you can easily differentiate between allowances and expectations:
context.checking(new Expectations() {{
// allowances
ignoring(parserState);
allowing(factory).create(); will(returnValue(object));
// expectations
one(service).addSth(with(any(Integer.class)), with(sth));
}});
Other powerful features are:
- Sequences: invocations in sequence.
- Argument matchers: hamcrest library
- States: constraint invocations when a condition is true.
精彩评论