我正在springockito-annotations 1.0.9
用于集成测试.
我有以下控制器:
@Autowired
public Controller(
@Qualifier("passwordService ") PasswordService passwordService ,
@Qualifier("validator") Validator validator,
@Qualifier("reportService") ReportService reportService,
DateCalculator dateCalculator,
Accessor accessor){
this.passwordService = passwordService;
this.validator = validator;
this.reportService = reportService;
this.dateCalculator = dateCalculator;
this.accessor = accessor;
}
Run Code Online (Sandbox Code Playgroud)
在测试中,我将使用@ReplaceWithMock注释从上下文中替换bean .
但不幸的是,它仅适用于没有@Qualifier注释的依赖项.
也就是说,我的测试看起来像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(loader = SpringockitoAnnotatedContextLoader.class, classes = {TestContext.class})
public class ControllerTest {
@Autowired
@ReplaceWithMock
private PasswordService passwordService ;
@Autowired
@ReplaceWithMock
private Validator validator;
@Autowired
@ReplaceWithMock
private ReportService reportService;
@Autowired
@ReplaceWithMock
private DateCalculator dateCalculator; …
Run Code Online (Sandbox Code Playgroud) java integration-testing unit-testing spring-mvc springockito
假设我有一个这样的类:
public class MyClass {
Dao dao;
public String myMethod(Dao d) {
dao = d;
String result = dao.query();
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
我想用mockito测试它.所以我创建了一个模拟对象,并以这种方式调用方法进行测试:
Dao mock = Mockito.mock(Dao.class);
Mockito.when(mock.myMethod()).thenReturn("ok");
new MyClass().myMethod(mock);
Run Code Online (Sandbox Code Playgroud)
但是,假设我有一个这样的类:
public class MyClass {
Dao dao = new Dao();
public String myMethod() {
String result = dao.query();
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我不能把我的模拟作为一个论点,所以我将如何测试我的方法?有人可以举个例子吗?
我有一个类(PriceSetter),我正在使用 Mockito 进行测试,并且该类具有内部依赖项(数据库)。我想模拟这个内部依赖项,然后将其注入到类中,但是我的构造函数中没有指定依赖项。因此,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
}
}
Run Code Online (Sandbox Code Playgroud)
我预计priceTable
会被注射,但没有被注射。只有d1和d2是通过构造函数注入注入的。
我有:
SomeClass a = spy(SomeClass.class)
Run Code Online (Sandbox Code Playgroud)
SomeClass
有private int myValue
。
我想设置myVlaue
为3。
我怎样才能使用 Mockito 做到这一点?
(如果 Mockito 不可能,那么我的下一个最佳选择是什么,最好不必放弃使用 Mockito 的代码)。
笔记:
getMyValue()
,我已经知道我可以做到这一点。setMyValue(int newMyValue)
,我不想要。