Skip to content
Advertisement

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

Advertisement

Answer

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"
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement