首页 > 解决方案 > 在使用 new 关键字创建的对象上使用 mockito

问题描述

class Check{
@Autowired
As400 as400; // Is a class that creates a connection to an external system
 
Public void execute(){
CommandCall commandCall = new CommandCall(as400);  // is a class that takes the 
                                                   // connection and enables us to 
                                                   // execute commands on the external 
                                                   //system
 response = commandCall.callExternalService();
}
}
Class Checktest{

@InjectMock
Check check;

@Mock
As400 as400

@Test()
public void testExternalService(){

}

要编写测试,我可以模拟 As400 CommandCall 怎么样?我应该如何处理?当我在实现类中使用 new 关键字创建它时,我对如何在编写测试用例时使用模拟的 As400 感到困惑

上述编码方式也是一种好的做法吗?还是我没有编写可测试的代码?

以及在编写代码时我应该注意什么,以便编写测试用例

标签: spring-bootmockitotestngibm-midrange

解决方案


是的,您还应该使CommandCall该类可注入以轻松地对您的代码进行单元测试。您可以创建一个新的配置类并将您的CommandCall那里定义为一个 bean 并稍后在您的Check类中注入它

@Configuration
public class AppConfig {

  @Bean
  public CommandCall commandCall(As400 as400) {
   return new CommandCall(as400);
  }

}

然后你Check将只依赖CommandCall它,你可以像你已经做过的那样轻松地模拟它As400


推荐阅读