0

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

Harry Coder
  • 2,429
  • 2
  • 28
  • 32
ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
  • Are you using "test" profile for test? see it for example: https://stackoverflow.com/questions/38711871/load-different-application-yml-in-springboot-test. Add @ActiveProfiles("test") – User9123 Apr 23 '22 at 23:17

2 Answers2

2

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

Sergio Santiago
  • 1,316
  • 1
  • 11
  • 19
2

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"
    }
}
Harry Coder
  • 2,429
  • 2
  • 28
  • 32