[英]Catching application context error spring junit
I am writing junits for my spring boot based application, and my beans depends on some configuration parameters specified in application-.properties. 我正在为基于Spring Boot的应用程序编写Junit,并且我的bean依赖于application-.properties中指定的一些配置参数。 In my configuration class where I am generating beans, 在我生成bean的配置类中,
@Configuration
public class AppConfig{
@Value("${MyProperty}")
private String myProperty;
@Bean
public myBean bean1() throws MyException{
if(myProperty.contentEquals("abc"){
throw MyException("Value abc not allowed for bean1");
}
}
In my junit I want to detect this scenario , if in my junit I set the profile and run it errors out saying 'Application startup failed' and not reach my before method or test method. 在我的junit中,我想检测到这种情况,如果在我的junit中,我设置了配置文件并运行该错误,并说“应用程序启动失败”并且无法到达我的before方法或test方法。
How do I handle this so that the junit does not fail and I am able to detect the myexception as well. 我该如何处理,以便junit不会失败并且我也能够检测到myexception。 Basically what I need is the application context creation to fail, but my unit tests to pass. 基本上,我需要的是应用程序上下文创建失败,但是我的单元测试通过了。
Thanks ! 谢谢 !
beans depends on some configuration parameters specified in application-.properties bean取决于application-.properties中指定的一些配置参数
This can be controlled by the @ConditionalOnProperty
annotation directly on your bean definition. 可以直接在bean定义上使用@ConditionalOnProperty
批注来控制。 Therefore instead of throwing an exception in your test bean, you won't have it registered at all provided your config is not there: 因此,如果您的配置不存在,则不会在您的测试bean中引发异常,而根本不会注册它:
I am writing junits for my spring boot based application, and my beans depends on some configuration parameters specified in application-.properties. 我正在为基于Spring Boot的应用程序编写Junit,并且我的bean依赖于application-.properties中指定的一些配置参数。 In my configuration class where I am generating beans, 在我生成bean的配置类中,
@ConditionalOnProperty(name = "myProperty", havingValue = "'hiThere'")
@Bean
public myBean bean1() {
//..
}
If you want to invoke some SpEL
operation on the property you can use @ConditionalOnExpression
: 如果要对属性调用一些SpEL
操作,可以使用@ConditionalOnExpression
:
@ConditionalOnExpression("${myProperty}.contains('ere')")
@Bean
public myBean bean1() {
//..
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.