如何为手动依赖项注入创建模拟测试

时间:2019-04-23 08:46:13

标签: java unit-testing junit mockito powermock

我正在使用Java创建手动依赖项注入。我正在尝试为此创建Mockito测试。

由于我是Mockito的新手,所以以前只做过基于框架的事情。所以需要您的帮助下

//All Business logic holder class. It does not have any new operator. Even, it does not have any knowledge about the concrete implementations
class MyClass {

private MyProto a;
private B b;
private C c;

MyClass(MyProtoImpl a, B b, C c) {
 //Only Assignment
 this.a = a;
 this.b = b;
 this.c = c;
}

//Application Logic
public void doSomething() {
 a.startClient(c);
 //Do B specific thing
 //Do C specific thing
 }
}

//The Factory. All the new operators should be placed in this factory class and wiring related objects here.
class MyFactory {
 public MyClass createMyClass() {
   return new MyClass(new AImpl(), new BImpl(), new CImpl());
  }
}

class Main {
 public static void main(String args[]) {
  MyClass mc = new MyFactory().createMyClass();
  mc.doSomething();
 }
}

所以最后我需要实现两件事。

  1. 测试MyFactory类和MyClass
  2. 测试MyProtoImpl类。因此,通过这种方式,我可以获得整个代码覆盖率。因此,不仅Junit Mockito还需要覆盖MyProtoImpl MyFactory,而且还需要覆盖MyClass

1 个答案:

答案 0 :(得分:0)

通常,您要创建依赖项的模拟。从注释看来,您似乎想单独测试类,因此我建议对模块进行“单元测试”。我将引导您完成MyClass的测试。

class MyTestClass {

    // First you want to create mocks of your dependencies
    @Mock
    MyProto a;

    @Mock
    B b;

    @Mock
    C c;

    // At this point Mockito creates mocks of your classes.
    // Calling any method on the mocks (c.doSomething()) would return null if the
    // method had a return type.

    @Test
    void myFirstTest(){
     // 1. Configure mocks for the tests
     // here you configure the mock's returned values (if there are any).
     given(a.someMethod()).willReturn(false);

     // 2. Create the SUT (Software Under Test) Here you manually create the class
     // using the mocks.
     MyClass myClass = new MyClass(a, b, c);

     // 3. Do the test on the service
     // I have assumed that myClass's doSomething simply returns a.someMethod()'s returned value
     boolean result = myClass.doSomething();

     // 4. Assert
     assertTrue(result);
     // Alternatively you can simply do:
     assertTrue(myClass.doSomething());
    }
}

如果您的类包含void方法,则可以测试是否已使用正确的参数调用了这些方法:

     verify(a).someMethod(someParameter);

这对Mockito差不多。创建模拟,设置所需的行为,最后声明结果或验证是否已使用正确的参数调用了方法。

但是,我认为负责数据库连接和类似配置的“ Mockito测试”类没有太大意义。 Mockito测试更适合IMHO测试应用程序的服务/逻辑层。如果您有一个Spring项目,那么我将在建立与数据库的真实连接的情况下简单地测试此类配置类(即数据库配置等)。