我如何在课堂上模拟Mockito其他正在测试的课程?
例如:
MyClass.java
class MyClass {
public boolean performAnything() {
AnythingPerformerClass clazz = new AnythingPerformerClass();
return clazz.doSomething();
}
}
AnythingPerformerClass.java
class AnythingPerformerClass {
public boolean doSomething() {
//very very complex logic
return result;
}
}
并测试:
@Test
public void testPerformAnything() throws Exception {
MyClass clazz = new MyClass();
Assert.assertTrue(clazz.performAnything());
}
我可以欺骗AnythingPerformerClass
从AnythingPerformerClass
排除不必要的逻辑吗?我可以覆盖简单返回doSomething()
或true
的<{1}}方法吗?
为什么我指定Mockito,因为我需要使用Robolectric进行Android测试。
答案 0 :(得分:15)
您可以重构MyClass
,以便它使用dependency injection。您可以将类的实例传递给AnythingPerformerClass
的构造函数,而不是让它创建MyClass
实例,如下所示:
class MyClass {
private final AnythingPerformerClass clazz;
MyClass(AnythingPerformerClass clazz) {
this.clazz = clazz;
}
public boolean performAnything() {
return clazz.doSomething();
}
}
然后,您可以在单元测试中传递模拟实现
@Test
public void testPerformAnything() throws Exception {
AnythingPerformerClass mockedPerformer = Mockito.mock(AnythingPerformerClass.class);
MyClass clazz = new MyClass(mockedPerformer);
...
}
或者,如果您的AnythingPerformerClass
包含州,则可以将AnythingPerformerClassBuilder
传递给构造函数。
答案 1 :(得分:3)
目前正如(方法中AnythingPerformerClass
的声明和实例化一样,仅使用Mockito模拟AnythingPerformerClass
是不可能的。
如果可能,将AnythingPerformerClass
的声明和实例化移动到类级别:声明类型为AnythingPerformerClass
的实例变量,并使其由构造函数实例化。
这样,您可以在测试期间更轻松地注入AnythingPerformerClass
的模拟,并指定其行为。例如:
when(anythingPerformerClassMock.doSomething()).thenReturn(true);
或测试错误处理:
when(anythingPerformerClassMock.doSomething()).thenTrow(new NullPointerException());
答案 2 :(得分:-1)
您可以在Mockito中设置要返回的内容。
when(mock.method()).thenReturn(someValue)