Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve Spring @Value expression in JUnit tests

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?

like image 771
Harold L. Brown Avatar asked Jan 02 '14 09:01

Harold L. Brown


People also ask

Can we use @value in JUnit?

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.

What is SpringJUnitConfig?

@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.

What is @after in JUnit?

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.

What is SpringBootTest annotation?

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.


1 Answers

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.

like image 161
nobeh Avatar answered Sep 23 '22 05:09

nobeh