spring-boot - 在使用 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 感到困惑
上述编码方式也是一种好的做法吗?还是我没有编写可测试的代码?
以及在编写代码时我应该注意什么,以便编写测试用例
解决方案
是的,您还应该使CommandCall
该类可注入以轻松地对您的代码进行单元测试。您可以创建一个新的配置类并将您的CommandCall
那里定义为一个 bean 并稍后在您的Check
类中注入它
@Configuration
public class AppConfig {
@Bean
public CommandCall commandCall(As400 as400) {
return new CommandCall(as400);
}
}
然后你Check
将只依赖CommandCall
它,你可以像你已经做过的那样轻松地模拟它As400
推荐阅读
- amazon-web-services - NACL 设置到通过 nat 网关连接到 Internet 的私有子网
- r - 根据我的范围规范我的表
- javascript - 我如何从开始时间中减去结束时间而不在 Javascript 计时器中有负分钟
- virtual-machine - 让虚拟机对应用程序来说就像是真实的机器
- machine-learning - 为什么使用 make_friedman1?
- javascript - 无法删除 [object Array] 的属性“1”
- android - 如何在for()循环中将android背景颜色设置为几个线性布局?
- reactjs - Redux-thunk “调度不是函数”
- kotlin - 如何从计时器中获取秒数?(Kotlin)
- c# - SQL Server 与 Unity 的连接