不能使用不同钻石操作员类别的同一类别的 2 个模拟



我有如下的类结构:

public interface Foo<T extends Bar>{
Optional<T> find();
}
public class A extends Bar{}
public class B extends Bar{}
@Service
@RequiredArgsConstructor
public class C{
Foo<A> a;
Foo<B> b;
B bInstance = b.find();
}
public class CTest{
@Mock
Foo<A> a;
@Mock
Foo<B> b;
@InjectMocks
C c;
@Test
public void testSomething(){
when(a.someMethod()).thenReturn(someVariable);
when(b.someMethod()).thenReturn(someOtherVariable);
}
}

那么我可能在C类中有一些代码,比如:

B bInstance = b.find();

这里的问题是,当find被调用时,它从类a而不是B返回一个新的实例,即从模拟a而不是模拟B的变量。因此,我得到一个classloadeexception之后做一些工作。

这应该像预期的那样工作,还是由模拟来自2个不同的钻石操作符类的同一类(Foo)的2个变量引起的问题(这是怎么叫的?)(a和B) Mockito无法解释?我还遗漏了什么吗?这可能不是足够的信息来做后续工作,但希望有一些概念上的误解,我有,可以很容易地解决。

提前感谢!

我要自己创建测试对象

public class CTest{
@Mock
Foo<A> a;
@Mock
Foo<B> b;
// @InjectMocks  since it is not working for you, lets skip it
C service;
@Before
public void setup(){
service=new C(a,b);
}
@Test
public void testSomething(){
when(a.someMethod()).thenReturn(someVariable);
when(b.someMethod()).thenReturn(someOtherVariable);
}
}

最新更新