【发布时间】:2019-06-10 19:37:15
【问题描述】:
我有一个使用 Mockito 测试的类 (PriceSetter),并且该类具有内部依赖项(数据库)。我想模拟这个内部依赖,然后将它注入到类中,但是我的构造函数中没有指定依赖。因此,Mockito 会自动尝试进行构造函数注入,并且永远不会注入依赖项。
我尝试在我的数据库对象上使用@Mock,在我的 PriceSetter 类上使用@InjectMocks,但 Mockito 自动调用构造函数,并且由于数据库未传递到构造函数中,它无法注入我的数据库模拟。
class PriceSetter {
private Table priceTable;
public PriceSetter(Dependency d1, Dependency d2) {
this.d1 = d1;
this.d2 = d2;
}
}
@RunWith(MockitoJUnitRunner.class)
class PriceSetterTest{
@InjectMocks
private PriceSetter setter;
@Mock Table priceTable;
@Mock Dependency d1;
@Mock Dependency d2;
@Test
public void someTestMethod() {
when(priceTable.getItem(any())).thenReturn(Specified item);
setter.priceTable.getItem("item"); -> Doesn't return item specified by mocked behavior
}
}
我希望priceTable 被注入,但它没有被注入。只有 d1 和 d2 是通过构造函数注入来注入的。
【问题讨论】:
-
priceTable 是如何设置的?一个setter方法?
-
Injectmocks 实际上应该使用反射来设置所有字段。您确定这里的所有设置都正确吗?
-
这取决于 priceTable 在真实类中的设置方式。
标签: java dependency-injection mockito