当Controller在不同的程序包JUnit5中时,MockMvc不起作用

问题描述

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);
}

}

这是我的模拟测试。它仅在控制器处于同一模块的测试中时才有效,否则,当我拆分项目时,它将返回404错误代码,因为未找到端点。

有人在多模块spring-boot应用程序中使用过MockMvc吗?

解决方法

使用@WebMvcTest注释解决

item_lists = [
    ['name1','pic1'],['name2','pic2'],# etc.
]

del item_lists[1]

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...