Reputation: 771
So basically I want to create a mockito unit test which returns a generic type and it's essential for me that I verify that method do return specific object-types. Any idea or tips on this would be helpful.
class Example {
public AnotherClass<T> generateExampleType( String args ) {
return new AnotherClass<T> (args);
}
}
class Another {
String method1(Type1 a) {
//
}
String method2(Type2 a) {
//
}
}
class ClassUnderTest{
public void methodUnderTest() {
// code
AnotherClass<Type1> obj1 = helper.<Type1>generateExampleType("abc");
AnotherClass<Type2> obj2 = helper.<Type2>generateExampleType("def");
String one = another.method2(obj2);
String two = another.method1(obj1); // this fails as part of verify in unit test
// code
}
}
Test
when(helper.<Type1>generateExampleType(anyString()).thenReturn(Obj1Mock);
when(helper.<Type2>generateExampleType(anyString()).thenReturn(Obj2Mock);
verify(another).method2(Obj2Mock);
verify(another).method1(Obj1Mock); // This fails expected Obj1, actually passed Obj2
Both Obj1 and Obj2 are used as part of other method invocation in the same workflow. However, mockito always defaults to the last created(obj2 in this instance) and my unit tests fail
/*
Expected class - Type1
Actually invoked - Type2
*/
Upvotes: 1
Views: 1894
Reputation: 771
Finally got the solution which was required. This should solve the issue and it did for me :-
http://www.agilearts.nl/tasty-test-tip-using-argumentcaptor-for-generic-collections-with-mockito/
Upvotes: 1