I have the following Controller class
@Component
public class Controller{
@Value("${details}")
private String detail1;
@Value("${otherdetails}")
private String detail2;
public ModelClass getSomeDetails(String name, int age) {
Serviceclass serviceobject = new Serviceclass();
//some Code
serviceobject.doSomething(name, age, detail1, detail2);
}
}
Once this is done, I need to test this method in a test case. My test class is as below. I have the application.properties file in the /src/test/resources folder
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations="classpath:application.properties")
public class testClass{
@Test
public void getDetails() {
Controller controllerObject = new Controller();
controllerObject.getSomeDetails("name", 22);
//Other code
}
}
When I do this, the application.properties has the details and otherdetails parameter but it is returning null.
How should I use them to get the value in the Controller class?
2 Answers 2
Do not manually instantiate the controller, rather AutoWire the controller into your test class.
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations="classpath:application.properties")
public class testClass{
@Autowired Controller controllerObject;
@Test
public void getDetails() {
controllerObject.getSomeDetails("name", 22);
//Other code
}
}
1 Comment
You need to let Spring instantiate your Controller class and not manually do a new yourself:
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations="classpath:application.properties")
public class testClass{
@Autowired
private Controller controllerObject;
@Test
public void getDetails() {
controllerObject.getSomeDetails("name", 22);
//Other code
}
@TestConfiguration
static class TestConfig {
@Bean
public Controller controller() {
return new Controller();
}
}
}
Note that you can also replace @RunWith(SpringJUnit4ClassRunner.class) with @RunWith(SpringRunner.class).
Instead of adding the inner class, you can also have Spring test start your complete application by annotating the test with @SpringBootTest. If you know what part of your application you want to test, you can get better performance by using test slicing.
3 Comments
@SpringBootTest, but I still get null for the values from the property files@TestPropertySource(properties="details=x"). See baeldung.com/spring-test-property-source
src\main\resources\application.propertiesis the structure right??@TestPropertySource(locations="classpath:application.properties")should be fine.