我有以下类(class)。 DataServices 对象在 ProductImpl 和 Mapper 中都使用。但它的模拟在 ProductImpl 中可用,但在 Mapper 类中不可用。我不知道需要做什么,以便在 Mapper 类中也可以使用 DataServices 的模拟。
class ProductImpl{
@Inject private DataServices ds;
@Inject private Mapper mapper;
public void call(){
ds.get(); //ds is not null here
mapper.map();
// some code
}
}
abstact class Mapper{
@Inject private DataServices ds;
public void map(){
ds.get()// ds is null here
//some code
}
}
我有下面的测试课
class Test{
@Mock private DataServices ds;
@Mock private Mapper mapper;
@InjectMocks private ProductImpl impl;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this)
}
@Test
public void test(){
impl.call();
}
}
最佳答案
如果我理解正确,那么您不需要在 Mapper 中进行另一次模拟,因为您已经模拟了映射器类,并且 map 方法也是无效的,尽管如果方法返回了某些内容,您可以轻松地使用 when
来提供您在测试中需要的行为。
关于java - 如何在Java中将一个模拟对象注入(inject)另一个模拟对象的模拟中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038658/