微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决当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]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。