【发布时间】:2016-12-08 01:09:14
【问题描述】:
所以基本上我想创建一个返回泛型类型的模拟单元测试,对我来说,验证该方法确实返回特定的对象类型是必不可少的。对此的任何想法或提示都会有所帮助。
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
*/
【问题讨论】:
-
为什么要返回泛型类型?
-
generateExampleType方法没有类型参数。 -
@Tim - 我想返回一个泛型,它是庞大工作流程的一部分
-
@Bubletan 它返回一个特定类型,我确实需要它
标签: java unit-testing junit mocking mockito