@Captor
This annotation will automatically create typed argument captors (
org.mockito.ArgumentCaptor<T>
) in your unit tests. Argument captors are essential in verifying indirect outputs to your mocked collaborators.
public class Test{
@Captor ArgumentCaptor<Foobar> foobarCaptor;
@Before
public void init(){
MockitoAnnotations.init(this);
}
@Test
public void shouldDoSomethingUseful() {
//...
verify(mock.doStuff(foorbarCaptor.capture()));
Foobar capturedFoobar = foobarCaptor.getValue();
assertEquals("foobar", capturedFoobar.getName());
}
}
@InjectMocks
Automatically injects mocks by type using setter injection. Constructor injection is not currently available, but if you want to provide a patch, the mockito team will gladly consider your contribution. I'm actually more interested in reflection-based injection, similar to what Spring uses when annotating dependency fields using @Autowired. Having your unit tests inject dependencies via reflection would help me avoid the set* methods on the implementations. I may have to play with this a bit.
public class FooBarManagerTests {
@Mock private FooDependency mockFoo;
@Mock private BarDependency mockBar;
@InjectMocks private FooBarManager manager = new FooBarManagerImpl();
@Before
public void initMocks() {
// Initializes all mocks and then injects those mocks into the FooManager instance.
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldDoSomething() {
manager.doSomething();
verify(mockFoo).doSomethingToFoo(any(String.class));
verify(mockBar).doSomethingToBar(any(Integer.class));
}
}
What aboout integration with spring managed test? Can i annotate a class with these both
ReplyDelete@RunWith(MockitoJUnitRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
Great and Useful Article.
ReplyDeleteJava Online Course
Java Online Training
Java EE training
Java Course in Chennai
Java Training in Chennai
Java Training Institutes in Chennai
Java Interview Questions
Java Interview Questions
Thank you for the great post!
ReplyDeleteVisit Best Astrologer in Vikarabad
Very amazing blog post,Thank you.
ReplyDeletelook here
Best Sofa Repair Services in Madivala