Home > Net >  How to initialize Repository in Testing-Environment?
How to initialize Repository in Testing-Environment?

Time:11-08

I want to test one of my Controllers, which originally accesses to my Service. My Service then initializes the Repository to store data. In my ControllerTest.java I am annotating the Repository and Service I need with @Mockbean, but I am getting the Error that for example the Repository-Attribute isn't initialized and is null.

This is how the beginning looks like:

@ExtendWith(SpringExtension.class)
//In this test, we want to launch only StudentController. All other controllers and mappings will not be launched when this unit test is executed.
@WebMvcTest(value = TodoController.class)
@WithMockUser
public class TodoControllerTest {

    // To launch only TodoController
        @Autowired
    private MockMvc mockMvc;

        @MockBean
    private TodoService todoService;

    @MockBean
    private ToDoRepository todoRepository;

    @Test
    public void retrieveDetailsForEintrag() throws Exception {
        Todo mockTodo = new Todo("Drink", "01.11.2022");
        todoRepository.save(mockTodo); //FIRST ERROR HERE

How can i initialize them in the Testingclass? Thanks!

Even though this is a Unit Test and I didn't want to import dependencies or other classes, I was thinking to import the Repository.

CodePudding user response:

Why you don't org.mockito.Mockito.when(todoRepository.save(org.mockito.ArgumentMatchers.any(Todo.class))).then(....

By the way, consider testing your layers separately: TodoControllerTest to test the TodoController's method is being invoked and returns something (like mockMvc.perform(..)..andExpect(status().isOk())), and another TodoServiceTest to test the real work (after all, the controller just delegates the request further, and returns the response): There mock the calls to the repository, and verify the service does it work.

And the most important thing, try to use some real repository layer, like H2. Sometimes from too much mocking, you don't really test your code.

  • Related