Verify object attribute value with mockito

New feature added to Mockito makes this even easier, ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class); verify(mock).doSomething(argument.capture()); assertEquals(“John”, argument.getValue().getName()); Take a look at Mockito documentation In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments: verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture()); assertEquals(“John”, argument.getValue().getName());

Mockito. Verify method arguments

An alternative to ArgumentMatcher is ArgumentCaptor. Official example: ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class); verify(mock).doSomething(argument.capture()); assertEquals(“John”, argument.getValue().getName()); A captor can also be defined using the @Captor annotation: @Captor ArgumentCaptor<Person> captor; //… MockitoAnnotations.initMocks(this); @Test public void test() { //… verify(mock).doSomething(captor.capture()); assertEquals(“John”, captor.getValue().getName()); }

How to mock a final class with mockito

Mockito 2 now supports final classes and methods! But for now that’s an “incubating” feature. It requires some steps to activate it which are described in What’s New in Mockito 2: Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to … Read more

How to capture a list of specific type with mockito

The nested generics-problem can be avoided with the @Captor annotation: public class Test{ @Mock private Service service; @Captor private ArgumentCaptor<ArrayList<SomeType>> captor; @Before public void init(){ MockitoAnnotations.initMocks(this); } @Test public void shouldDoStuffWithListValues() { //… verify(service).doStuff(captor.capture())); } }

Mockito : how to verify method was called on an object created within a method?

Dependency Injection If you inject the Bar instance, or a factory that is used for creating the Bar instance (or one of the other 483 ways of doing this), you’d have the access necessary to do perform the test. Factory Example: Given a Foo class written like this: public class Foo { private BarFactory barFactory; … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)