Here's a snippet of a Spring bean:
@Component
public class Bean {
@Value("${bean.timeout:60}")
private Integer timeout;
// ...
}
Now I want to test this bean with a JUnit test. I'm therefore using the SpringJUnit4ClassRunner and the ContextConfiguration annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class BeanTest {
@Autowired
private Bean bean;
// tests ...
@Configuration
public static class SpringConfiguration {
@Bean
public Bean bean() {
return new Bean();
}
}
}
Unfortunately the SpringJUnit4ClassRunner can't resolve the @Value
expression, even though a default value is supplied (a NumberFormatException is thrown). It seems that the runner isn't even able to parse the expression.
Is something missing in my test?
With the @ValueSource annotation, we can pass an array of literal values to the test method. As we can see, JUnit will run this test two times and each time assigns one argument from the array to the method parameter.
@SpringJUnitConfig is a composed annotation that combines @ExtendWith(SpringExtension. class) from JUnit Jupiter with @ContextConfiguration from the Spring TestContext Framework. As of Spring Framework 5.3, this annotation will effectively be inherited from an enclosing test class by default.
org.junit Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception.
The @SpringBootTest annotation tells Spring Boot to look for a main configuration class (one with @SpringBootApplication , for instance) and use that to start a Spring application context.
Your test @Configuration
class is missing an instance of PropertyPlaceholderConfigurer
and that's why Spring does not know how to resolve those expressions; add a bean like the following to your SpringConfiguration
class
@org.springframework.context.annotation.Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setIgnoreResourceNotFound(true);
return ppc;
}
and move it to a separate class and use
@ContextConfiguration(classes=SpringConfiguration.class)
to be more specific when running your test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With