被测试的类中的模拟类

时间:2013-07-19 09:52:17

标签: java unit-testing junit4 mockito robolectric

我如何在课堂上模拟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());
}

我可以欺骗AnythingPerformerClassAnythingPerformerClass排除不必要的逻辑吗?我可以覆盖简单返回doSomething()true的<{1}}方法吗?

为什么我指定Mockito,因为我需要使用Robolectric进行Android测试。

3 个答案:

答案 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)