所以基本上我想创建一个返回通用类型的模拟单元测试,对我来说验证该方法确实返回特定对象类型至关重要。任何关于这方面的想法或提示都会有帮助。
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
}
}
测试
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
Obj1 和 Obj2 都用作同一工作流程中其他方法调用的一部分。但是,mockito 始终默认为最后创建的(在本例中为 obj2),并且我的单元测试失败
/*
Expected class - Type1
Actually invoked - Type2
*/
最佳答案
终于得到了所需的解决方案。这应该可以解决问题,它对我来说是这样的:-
http://www.agilearts.nl/tasty-test-tip-using-argumentcaptor-for-generic-collections-with-mockito/
关于java - Mockito - 返回通用类型(多个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030117/