Mockito:没有成员但内联创建的模拟对象 [英] Mockito: Mock object which is no member but is created inline
问题描述
我有一个类,它执行以下操作:
I have a class which does the following:
public class Transformer {
public void transform(final Car car) throws IOException {
switch (car.getType()) {
case OFFROAD:
OffroadCar offroadCar = new OffroadTransformer().transform(car);
// do something with offorad car
break;
...
}
}
}
我有一个测试类:
public class TransformerTest {
@InjectMocks
private Transformer transformer;
@Mock
private OffroadTransformer offroadTransformer;
@BeforeEach
public void setup()
MockitoAnnotations.initMocks(this);
}
@Test
public void testTransform() throws IOException {
final Car car = new Car(OFFROAD);
when(offroadTransformer.transform(any(Car.class))).thenReturn(new OffroadCar());
transformer.transform(car);
// make some verifictations
}
}
我现在的问题是 when
不起作用.调用真正的 offroadTransformer.transform
而不是模拟.所以我的假设是模拟不起作用,因为 OffroadTransformer
不是 Transformer
类的成员,并且实例是内联创建的.
My problem now is that the when
is not working. The real offroadTransformer.transform
is called instead of the mock. So my assumption is that the mock is not working because the OffroadTransformer
is no member of the class Transformer
and the instance is created inline.
正确吗?
如果是:我怎么能嘲笑它?如果不是:还有什么可能是原因?
If yes: How can I anyway mock it? If no: What else could be the cause?
推荐答案
问题是正在使用的 OffroadTransformer
对象没有被模拟.您的测试设置正在 transformer
字段中创建一个模拟,但该模拟不是该方法使用的模拟,这证实了您的假设.
The problem is that the OffroadTransformer
object being used is not mocked. Your test setup is creating a mock in the transformer
field, but this mock is not the one being used by the method, and that confirms your hypothesis.
您使用的设置适用于将模拟对象作为实例字段的类,如下所示:
The setup you're using works with classes that have mocked objects as instance fields, like this:
public class Transformer {
//injected, initialized inline, etc.
private OffroadTransformer transformer;
public void transform(final Car car) throws IOException {
switch (car.getType()) {
case OFFROAD:
OffroadCar offroadCar = this.transformer.transform(car);
// do something with offorad car
break;
...
}
}
}
在这样的类中,Mockito 将注入模拟,方法执行将使用由 Mockito 创建的模拟.
Into such a class, Mockito would inject the mock and the method execution would use that mock created by Mockito.
如果您不想使用此设置,那么您可能需要查看类似 模拟你的 OffroadTransformer
的构造函数.
If you do not want to use this set up, then you may want to look into something like mocking the constructor of your OffroadTransformer
.
另一方面,对于诸如 OffroadTransformer
之类的工厂类来说,没有状态并用作单例是相当普遍的做法.因此,遵循上述设置并让 Mockito 为您处理注入更为自然.
On a side note, however, it's rather common practice for factory classes such as OffroadTransformer
to have no state and to be used as singletons. It's therefore more natural to follow the setup mentioned above and let Mockito handle the injection for you.
这篇关于Mockito:没有成员但内联创建的模拟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!