MockMvc Not working when Controller is in different package (JUnit5)

873 views Asked by At
package com.azry.ptm.api;

import com.azry.ptm.api.model.account.AccountDTO;
import com.azry.ptm.domain.account.Account;
import com.azry.ptm.server.services.AccountService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest; 
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.anyLong;


@AutoConfigureMockMvc
@SpringBootTest
public class AccountControllerImplTest {

@Autowired
private MockMvc mockMvc;

@MockBean
public AccountService accountService;

@Test
public void test() throws Exception {

    final long entityNo = 10;
    Account expectedAccount = Account.builder()
            .entityNo(entityNo)
            .build();
    Mockito.when(accountService.getAccountById(anyLong())).thenReturn(Optional.of(expectedAccount));


    MockHttpServletResponse response = mockMvc.perform(ControllerTestHelper.makeGetRequest("account/", String.valueOf(entityNo)))
            .andReturn()
            .getResponse();
    AccountDTO responseAccount = ControllerTestHelper.toObject(response.getContentAsString(), AccountDTO.class);


    assertEquals(HttpStatus.OK.value(), response.getStatus());
    assertNotNull(responseAccount);
}

}

Here is my mockMvc test. it works only when the controller is in the same module es test, otherwise, when I split the project it returns a 404 error code as no endpoint was found.

has anybody experience using mockMvc in a multi-module spring-boot app?

1

There are 1 answers

0
Tornike Kechakmadze On

solved using @WebMvcTest annotation

@WebMvcTest(AccountControllerImpl.class)