何时使用新运算符创建 obj 以及何时使用自动装配注释来测试 class?
When to use a new operator to create obj and when to use autowired annotation to test a class?
我要测试的 class 调用 UserService
with sendEmail
方法,它会向用户发送一封电子邮件。
完成这项任务取决于EmailService
。现在,在编写测试用例来测试它时——我应该创建 UserService userService = new UserService()
并模拟电子邮件服务,还是创建上下文文件定义 UserService
bean 并在我的测试 class 中定义 @Autowired UserService
并模拟 EmailService
?
这两种方法有什么区别?我什么时候应该使用其中一种?其中哪一个是真实的对象?
如果您的 class 是一个 bean,例如您还希望注入依赖项,则您应该不 使用 new运算符。请检查 inject-doesnt-work-with-new-operator answer
您可以创建一个 TestConfig.class
并模拟 UserService
的依赖项(使用您喜欢的模拟框架 - 我更喜欢 mockito)。在此 TestConfig 中,您创建 bean:
@Configuration
public static class TestConfig {
@Bean
private EmailService emailService() {
return Mockito.mock(EmailService.class);
}
//Assuming that you have constructor injection.
@Bean
public UserService userService() {
return new UserService(emailService());
}
}
我要测试的 class 调用 UserService
with sendEmail
方法,它会向用户发送一封电子邮件。
完成这项任务取决于EmailService
。现在,在编写测试用例来测试它时——我应该创建 UserService userService = new UserService()
并模拟电子邮件服务,还是创建上下文文件定义 UserService
bean 并在我的测试 class 中定义 @Autowired UserService
并模拟 EmailService
?
这两种方法有什么区别?我什么时候应该使用其中一种?其中哪一个是真实的对象?
如果您的 class 是一个 bean,例如您还希望注入依赖项,则您应该不 使用 new运算符。请检查 inject-doesnt-work-with-new-operator answer
您可以创建一个 TestConfig.class
并模拟 UserService
的依赖项(使用您喜欢的模拟框架 - 我更喜欢 mockito)。在此 TestConfig 中,您创建 bean:
@Configuration
public static class TestConfig {
@Bean
private EmailService emailService() {
return Mockito.mock(EmailService.class);
}
//Assuming that you have constructor injection.
@Bean
public UserService userService() {
return new UserService(emailService());
}
}