在使用 new 关键字创建的对象上使用 mockito
Using mockito on Objects created using new Keyword
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 呢?我该如何处理?当我在实现 class 中使用 new 关键字创建它时,我对在编写测试用例时如何使用模拟的 As400 感到困惑
而且上述编码方式也是一种好的做法吗?还是我没有编写可测试的代码?
以及在写代码的时候应该注意什么,才能轻松写出测试用例
是的,您还应该使 CommandCall
class 可注入,以便轻松地对您的代码进行单元测试。您可以创建一个新配置 class 并将您的 CommandCall
定义为一个 bean,稍后将其注入您的 Check
class
@Configuration
public class AppConfig {
@Bean
public CommandCall commandCall(As400 as400) {
return new CommandCall(as400);
}
}
然后你的 Check
将只依赖于 CommandCall
,你可以像你已经用 As400
那样轻松地模拟它
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 呢?我该如何处理?当我在实现 class 中使用 new 关键字创建它时,我对在编写测试用例时如何使用模拟的 As400 感到困惑
而且上述编码方式也是一种好的做法吗?还是我没有编写可测试的代码?
以及在写代码的时候应该注意什么,才能轻松写出测试用例
是的,您还应该使 CommandCall
class 可注入,以便轻松地对您的代码进行单元测试。您可以创建一个新配置 class 并将您的 CommandCall
定义为一个 bean,稍后将其注入您的 Check
class
@Configuration
public class AppConfig {
@Bean
public CommandCall commandCall(As400 as400) {
return new CommandCall(as400);
}
}
然后你的 Check
将只依赖于 CommandCall
,你可以像你已经用 As400