我刚刚开始用Mockito在Android上进行单元测试-如何让正在测试的类使用模拟类/对象而不是常规类/对象?
-
您可以为编写测试的类使用@InjectMocks。
@InjectMocks private EmployManager manager;
-
然后,您可以将@Mock用于正在嘲笑的类。这将是依赖类。
@Mock private EmployService service;
-
然后编写一个设置方法,使其可用于测试。
@Before public void setup() throws Exception { manager = new EmployManager(); service = mock(EmployService.class); manager.setEmployService(service); MockitoAnnotations.initMocks(this); }
然后写你的测试。
@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));
}
通过注入依赖项:
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
注释来注入私有字段(有关它们如何工作的详细解释,请阅读javadoc)。