gpt4 book ai didi

java - 如何为手动依赖注入(inject)创建mockito测试

转载 作者:行者123 更新时间:2023-12-02 06:24:01 24 4
gpt4 key购买 nike

我正在使用 java 创建手动依赖注入(inject)。我正在尝试为此创建 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

最佳答案

通常您想要创建依赖项的模拟。从评论来看,您似乎想单独测试这些类,因此我建议对模块进行“单元测试”。我将引导您完成 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 测试更适合测试应用程序的服务/逻辑层。如果您有一个 Spring 项目,我会简单地在一个场景中测试此类配置类(即数据库配置等),在该场景中我建立了与数据库的真实连接。

关于java - 如何为手动依赖注入(inject)创建mockito测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55807417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com