java - @MockBean 和 @Autowired 在一个测试类中的相同服务
问题描述
是否有可能以某种方式拥有相同的测试类@MockBean
和@Autowired
相同的服务?
换句话说,我@MockBean
只想为一个测试提供服务,而对于同一类的其他测试,我需要它作为@Autowired
.
解决方案
@MockBean
这取决于和之间的差异@Autowired
。
@Autowired
只在SpringContext
bean 中查找该类型的 bean。这意味着如果您需要“自动装配”它,您将需要创建该 bean
@MockBean
完全符合您对名称的期望,它创建了服务的“模拟”,并将其作为 bean 注入。
所以这
class MyTest {
@MockBean
MyService myService;
}
相当于这个
@Import(MyTest.Config.class)
class MyTest {
@Autowired
MyService myService;
@TestConfiguration
static class Config {
@Bean
MyService myService() {
return Mockito.mock(MyService.class);
}
}
}
因此,如果您需要在其他测试中使用不同类型的 bean,则需要在带注释的类MyService
中创建 bean@TestConfiguration
@Import(MyTest.Config.class)
class MyTest {
@Autowired
MyService myService;
@TestConfiguration
static class Config {
@Bean
MyService myService() {
return new MyServiceImpl();
}
}
}
或者,在一个带有注释的类中@Configuration
@Import(MyConfig.class)
class MyTest {
@Autowired
MyService myService;
}
@Configuration
public class MyConfig {
@Bean
MyService myService() {
return new MyServiceImpl();
}
}
推荐阅读
- python - 'list_display[2]' 的值指的是 'first_name',它不是可调用的、'UserAdmin' 的属性或 'authentication.User' 上的属性
- angular - 导航结束时隐藏 Ionic loader 问题
- winapi - 如何在 Windows 上查找所有字体路径
- swift - 适用于 iOS 的 MoPub:“目标未运行或缺少所需的目标权利”
- laravel-nova - BelongsToMany:nova 在 2 字模型“LongFeature”之间添加连字符
- perl - 带括号和不带括号的eof的区别?(Perl5)
- javascript - 无法覆盖 react-h5-audio-player scss 变量
- usb - stm32F407 usb-cdc接收中断和定时器中断不能同时工作
- laravel - laravel setEmailAttribute 模型等效于 spring boot kotlin
- javascript - 如何在 JS 中创建和填充类似的数组?