0


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.

Hülya
  • 3,353
  • 2
  • 12
  • 19
Manuel K.
  • 23
  • 8

1 Answers1

0

You need configure dataSource for test environment. If you use Spring Boot then try to create application.properties located in test/resources(Spring Boot will make everythin else)

for example, with h2 database

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

read part about dataSource properties in application.properties file https://www.baeldung.com/spring-testing-separate-data-source and Spring Boot Datasource in unit tests

or if you don't use Spring Boot then you need to configure your env for test another way, it depends on conventions and rules in your project. I think, in any case, you need to find dataBase configuration for real set-up (it will be dataSource bean and all related stuff) and try to emulate it(Add TestConfiguration and substitute all needed beans there(or use @Mock annotation)

Alex
  • 3,923
  • 3
  • 25
  • 43