【发布时间】:2013-08-12 11:16:08
【问题描述】:
我刚刚开始使用 Mockito 在 Android 上进行单元测试 - 如何让要测试的类使用模拟类/对象而不是常规类/对象?
【问题讨论】:
我刚刚开始使用 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 注释直接注入私有字段(阅读 the javadoc 以了解它们如何工作的详细说明)。
【讨论】: