Jag måste säga det – Mockito smakar väldigt bra. Tidigare använde jag EasyMock och jMock och idag läste jag mig in på JMockit, som skriver:
Design considerations for production code
The problem with imposing restrictions on the design of production code is that there are good reasons for making classes
final, for directly obtaining instances of collaborators with thenewoperator, and for using APIs based onstaticmethods. There is nothing inherently wrong with using these three Java language keywords, after all.
Fine. Jag kan köpa det. Men sedan går man vidare och säger
The JMockit mocking API is simple, consistent, and minimal.
Nu börjar det bli jobbigt att hålla med :) Låt oss ta deras exempelkod:
public void testDoOperationAbc(final DependencyXyz mock)
{
new NonStrictExpectations()
{
AnotherDependency anotherMock;
{ anotherMock.doSomething("test"); result = 123; }
};
new ServiceAbc().doOperation("some data");
new Verifications()
{{
mock.complexOperation(true, anyInt, null); times = 1;
}};
}
och så jämför vi med samma sak i Mockito:
public void testDoOperationAbc(final DependencyXYZ mock) {
when(anotherMock.doSomething("test")).thenReturn(123);
new ServiceAbc().doOperation("some data");
verify(mock.complexOperation(eq(true), anyInt(), eq(null)));
}
eller BDD-style:
public void doOperationCallsComplexOperation(final DependencyXYZ mock) {
// GIVEN
given(anotherMock.doSomething("test")).willReturn(123);
// WHEN
new ServiceAbc().doOperation("some data");
// THEN
verify(mock.complexOperation(eq(true), anyInt(), eq(null)));
}
I min värld är Mockito det mockningsramverk som är minst i vägen. För nyskriven kod vet jag vad mitt val faller på. Det är inte lika ”komplett” eller kraftfullt som andra ramverk, men så är det också inte i vägen. Måste man prompt använda final och static eller mocka privata metoder kan PowerMock hjälpa till.
