I have a REST controller in a Spring boot application, simplyfied:
@RestController
@RequestMapping("/api")
public class MyRestController {
@Autowired
private Environment env;
private String property1;
@PostConstruct
private void init() {
this.property1 = env.getProperty("myproperties.property_1");
}
@GetMapping("/mydata")
public String getMyData() {
System.out.println("property1: " + this.property1);
...
}
In application.yml I have defined the property similar to:
myproperties:
property_1: value_1
When I use the REST controller, it works as expected, the value value_1 is read, and in the GET method present.
Now I wanted to test it with a unit test, similar too:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class)
public class MyRestControllerTest {
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
private MockMvc restMyRestControllerMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final MyRestController myRestController = new MyRestController();
this.restMyRestControllerMockMvc = MockMvcBuilders.standaloneSetup(myRestController)
.setCustomArgumentResolvers(pageableArgumentResolver).setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService()).setMessageConverters(jacksonMessageConverter)
.build();
}
@Test
public void getMyDataTest() throws Exception {
restMyRestControllerMockMvc.perform(get("/api/mydata"))
.andExpect(status().isOk());
}
When the method in test is executed, the value of the property property1 is null.
Why is that?
The code above is partially generated by JHipster, I'm not sure if this is a optimal solution, just reused it.
Thanks!