I currently work on a Spring Project and I am now writing JUnit tests. My problem is, that the jdbcTemplate
is null (tested with Debugger) in the method getQuestions
, so it doesn't receive any data from the database.
Everything else works just fine. So here's my code:
I do this at the beginning of the controller class:
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Autowired
private JdbcTemplate jdbcTemplate;
getQuestions:
@PostMapping("/question")
public List<String> getQuestions(@RequestBody int number){
String query = "SELECT t.question " +
"FROM question as t " +
"ORDER BY RAND() " +
"LIMIT " + number + ";";
this.questionList = jdbcTemplate.queryForList(query, String.class);
this.index = number;
return questionList;
}
I do this at the beginning of the Test class:
private MockMvc mockMvc;
@InjectMocks
private MainController controller;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.build();
}
And the Test method:
@Test
public void getQuestions() throws Exception{
int num = 4;
mockMvc.perform(
MockMvcRequestBuilders.post("/api/question")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(asJsonString(num))
.accept(MediaType.APPLICATION_JSON_UTF8)
).andExpect(MockMvcResultMatchers.status().isOk());
}
Now I don't know how to get the jdbcTemplate
not to be null. Also in the regular application the method works perfectly fine.