[英]MockMvc Not working when Controller is in different package (JUnit5)
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.这是我的 mockMvc 测试。 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.
它仅在控制器位于同一模块 es 测试中时才有效,否则,当我拆分项目时,它会返回 404 错误代码,因为找不到端点。
has anybody experience using mockMvc in a multi-module spring-boot app?有没有人在多模块 spring-boot 应用程序中使用 mockMvc 的经验?
使用@WebMvcTest 注释解决
@WebMvcTest(AccountControllerImpl.class)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.