我在一个小型 PoC 中使用 Spring Boot,并且正在尝试测试 @Bean 实现。我有这个代码:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(@Value("${db.resetAndLoadOnStartup:true}") boolean resetAndLoadOnStartup,
SequenceIdRepository sequenceRepository,
UserAccountRepository userAccountRepository,
BookRepository bookRepository) {
return args -> {
log.info("Init Application...");
if (resetAndLoadOnStartup) {
fillDBData(sequenceRepository, userAccountRepository, bookRepository);
}
log.info("Aplication initiated!");
};
}
private void fillDBData(SequenceIdRepository sequenceRepository,
UserAccountRepository userAccountRepository,
BookRepository bookRepository) {
// Some code...
}
...
}
我如何对这个@Bean commandLineRunner进行单元测试?是的,也许我可以对“fillDBData”方法进行单元测试(受保护或使用 powermock),但我想了解是否有一种方法可以“完全”测试 Spring @Bean。
以下是如何使用集成测试进行测试。
@RunWith(SpringJUnit4ClassRunner.class)
// Or create a test version of Application.class that stubs out services used by the CommandLineRunner
@SpringApplicationConfiguration(classes = Application.class)
public class CommandLineRunnerIntegrationTest {
@Autowired
private CommandLineRunner clr;
@Test
public void thatCommandLineRunnerDoesStuff() throws Exception {
this.clr.run();
// verify changes...
}
}
话虽如此,我的偏好是创建一个实现命令行运行程序的命名服务,然后对其所有依赖项进行模拟,对其进行单元测试。在我看来,测试 Spring 在应用程序加载时是否调用 CommandLineRunner bean 并不重要,重要的是 CommandLineRunner 实现是否适当地调用其他服务。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)