我想测试我的Spring Boot命令行应用程序。我想模拟某些bean(可以通过@ContextConfiguration(classes = TestConfig.class)
在测试类的顶部进行注释来实现。在中TestConfig.class
,我覆盖了我想模拟的bean。我想Spring Boot
找到其余的组件。这似乎有效。
问题是,当我运行测试时,整个应用程序将正常启动(即,该run()
方法被调用)。
@Component
public class MyRunner implements CommandLineRunner {
//fields
@Autowired
public MyRunner(Bean1 bean1, Bean2 bean2) {
// constructor code
}
@Override
public void run(String... args) throws Exception {
// run method implementation
}
我尝试覆盖MyRunner
@Bean
并将其放入中TestConfig.class
,但这似乎不起作用。我知道我正在加载常规的应用程序上下文,但这就是我想做的(我认为吗?),因为我想重复使用@Component
我在应用程序中创建的所有(或大部分)I,并且仅模拟一小部分。
有什么建议?
编辑:
应用程序
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
答案比我想的要简单。在其中添加MockBean
@TestConfiguration
public class TestConfig {
@MockBean
private MyRunner myRunner;
}
我们可以使用@MockBean将模拟对象添加到Spring应用程序上下文中。该模拟将替换应用程序上下文中任何现有的相同类型的bean。
所以MyRunner.run()
从不被调用,但是我仍然可以在应用程序中使用所有其他bean。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句