'Spring Boot Test Cannot find Properties No Matter What

I have a simple bean

public class MyBean {

    @Value("${propItem}")
    private boolean propItem;

    public String someMethod() {
        if (propItem) {
            return "XX";
        } else {
            return "XY";
        }
    }
}

I have a properties file in src/test/resources called application-test.yml which has one property

propItem: true

If I run my test below - I expect it to pass, but it fails because propItem is always false

@SpringBootTest
public class MyBeanTest {
    public void testFunc() {
       assertTrue(new MyBean().someMethod().equals("XX"); // Fails because it's "XY"
    }
}

Why is this a problem? I thought Spring does all these automatically, but seems not



Solution 1:[1]

You need to:

  • define MyBean as a bean by adding an stereotype annotation: @Component, @Configuration or @Service
  • define an active profile on your test class: @ActiveProfile("test")

Your class should looks like this:

@Component
public class MyBean {

    @Value("${propItem}")
    private boolean propItem;

    public String someMethod() {
        if (propItem) {
            return "XX";
        } else {
            return "XY";
        }
    }
}

Your test class:

@SpringBootTest
@ActiveProfile("test")
public class MyBeanTest {

    @Autowired
    private MyBean myBean;

    @Test
    public void testFunc() {
       assertTrue(myBean.someMethod().equals("XX")); // Fails because it's "XY"
    }
}

Solution 2:[2]

You are instantiating mybean manually, this way the property will not be injected. You need to get the bean from the context.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harry Coder
Solution 2 Sergio Santiago