如何为手动依赖注入创建mockito测试

问题描述 投票:0回答:1

我正在使用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 MyFactory覆盖MyProtoImpl,还需要覆盖MyClass
java unit-testing junit mockito powermock
1个回答
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-test”类没有多大意义。 Mockito测试是IMHO更适合测试应用程序的服务/逻辑层。如果你有一个spring项目,我会在一个场景中测试这样的配置类(即数据库配置等),在那里我建立一个到数据库的真实连接。

© www.soinside.com 2019 - 2024. All rights reserved.