hot*_*oup 1 java junit unit-testing mockito spring-boot
这是我用于重现确切问题的GitHub 存储库。
不确定这是 Spring Boot 问题还是 Mockito 问题。
我有以下 Spring Boot@Component类:
@Component
class StartupListener implements ApplicationListener<ContextRefreshedEvent>, KernelConstants {
@Autowired
private Fizz fizz;
@Autowired
private Buzz buzz;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// Do stuff involving 'fizz' and 'buzz'
}
}
Run Code Online (Sandbox Code Playgroud)
SoStartupListener没有构造函数,并且故意是一个 Spring @Component,它通过@Autowired.
@Configuration提供这些依赖项的类在这里,作为一个很好的衡量标准:
@Configuration
public class MyAppConfiguration {
@Bean
public Fizz fizz() {
return new Fizz("OF COURSE");
}
@Bean
public Buzz buzz() {
return new Buzz(1, true, Foo.Bar);
}
}
Run Code Online (Sandbox Code Playgroud)
我现在正在尝试为 编写 JUnit 单元测试StartupListener,并且我一直在使用Mockito并取得了巨大的成功。我想创建一个模拟 Fizz和Buzz实例并注入StartupListener它们,但我不确定如何:
public class StartupListenerTest {
private StartupListener startupListener;
@Mock
private Fizz fizz;
@Mock
price Buzz buzz;
@Test
public void on_startup_should_do_something() {
Mockito.when(fizz.calculateSomething()).thenReturn(43);
// Doesn't matter what I'm testing here, the point is I'd like 'fizz' and 'buzz' to be mockable mocks
// WITHOUT having to add setter methods to StartupListener and calling them from inside test code!
}
}
Run Code Online (Sandbox Code Playgroud)
关于我如何做到这一点的任何想法?
请参阅我的GitHub 存储库以重现此确切问题。
您可以使用@SpyBean代替@MockBean,SpyBean包装真正的 bean,但允许您验证方法调用和模拟单个方法,而不会影响真正 bean 的任何其他方法。
@SpyBean
private Fizz fizz;
@SpyBean
price Buzz buzz;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3015 次 |
| 最近记录: |