Android 使用模拟对象
我刚刚用Mockito在Android上开始了单元测试-如何让正在测试的类使用模拟类/对象而不是常规类/对象?通过注入依赖项:Android 使用模拟对象,android,mocking,mockito,Android,Mocking,Mockito,我刚刚用Mockito在Android上开始了单元测试-如何让正在测试的类使用模拟类/对象而不是常规类/对象?通过注入依赖项: public class ClassUnderTest private Dependency dependency; public ClassUnderTest(Dependency dependency) { this.dependency = dependency; } // ... } ... Depend
public class ClassUnderTest
private Dependency dependency;
public ClassUnderTest(Dependency dependency) {
this.dependency = dependency;
}
// ...
}
...
Dependency mockDependency = mock(Dependency.class);
ClassUnderTest c = new ClassUnderTest(mockDependency);
您还可以使用setter注入依赖项,甚至可以使用@Mock
和@InjectMocks
注释直接注入私有字段(阅读以了解它们如何工作的详细说明)
@InjectMocks
私人雇员经理代码>
@Mock
私人就业服务代码>
@Test
public void testSaveEmploy() throws Exception {
Employ employ = new Employ("u1");
manager.saveEmploy(employ);
// Verify if saveEmploy was invoked on service with given 'Employ'
// object.
verify(service).saveEmploy(employ);
// Verify with Argument Matcher
verify(service).saveEmploy(Mockito.any(Employ.class));
}
你能给我一个答案吗。谢谢
@Test
public void testSaveEmploy() throws Exception {
Employ employ = new Employ("u1");
manager.saveEmploy(employ);
// Verify if saveEmploy was invoked on service with given 'Employ'
// object.
verify(service).saveEmploy(employ);
// Verify with Argument Matcher
verify(service).saveEmploy(Mockito.any(Employ.class));
}