spring基于MockMvc的controller测试

本文介绍了一个实用的SpringBoot单元测试工具类实现方法,通过创建TestControllerUtil工具类,简化了后续所有控制器测试类的编写过程。该工具类支持GET和POST请求测试,并展示了如何在HelloControllerTest测试类中使用它。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Component
public class TestControllerUtil {

    private MockMvc mockMvc;
    @Autowired
    private WebApplicationContext webApplicationContext;

    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
    }

    public MvcResult testGetRequest(String url, String contentType) throws Exception {
        return mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(contentType)).andReturn();
    }

    /**
     * @param url         请求的url 如 "/hello"
     * @param contentType 如:text/plain;charset=UTF-8
     * @param params      MultiValueMap继承map 实现 MultiValueMap map = new LinkedMultiValueMap<>();
     * @throws Exception
     */
    public MvcResult testPostRequest(String url, String contentType, MultiValueMap<String, String> params) throws Exception {
        return mockMvc.perform(MockMvcRequestBuilders.post(url)
                .params(params).accept(contentType))
                .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
    }

先写一个util工具类。以后的测试类都使用这个工具类自动注入。例如:


@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerTest {
    private Logger logger = LogManager.getLogger(HelloControllerTest.class);

    @Autowired
    private TestControllerUtil testControllerUtil;

    @Before
    public void setUp() {
        testControllerUtil.setUp();
    }

    @Test
    public void testHelloGEt() throws Exception {
        logger.info(testControllerUtil.testGetRequest("/hello", "text/plain;charset=UTF-8").getResponse().getContentAsString());

    }

    @Test
    public void testHelloPost() throws Exception {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("id", "san");
        logger.info(testControllerUtil.testPostRequest("/hello2", "text/plain;charset=UTF-8", map).getResponse().getContentAsString());

    }

}

然后运行
这里写图片描述

最后运行成功。这里写图片描述

Classes contained in spring-mock.jar: org.springframework.mock.jndi.ExpectedLookupTemplate.class org.springframework.mock.jndi.SimpleNamingContext.class org.springframework.mock.jndi.SimpleNamingContextBuilder.class org.springframework.mock.web.DelegatingServletInputStream.class org.springframework.mock.web.DelegatingServletOutputStream.class org.springframework.mock.web.HeaderValueHolder.class org.springframework.mock.web.MockExpressionEvaluator.class org.springframework.mock.web.MockFilterChain.class org.springframework.mock.web.MockFilterConfig.class org.springframework.mock.web.MockHttpServletRequest.class org.springframework.mock.web.MockHttpServletResponse.class org.springframework.mock.web.MockHttpSession.class org.springframework.mock.web.MockMultipartFile.class org.springframework.mock.web.MockMultipartHttpServletRequest.class org.springframework.mock.web.MockPageContext.class org.springframework.mock.web.MockRequestDispatcher.class org.springframework.mock.web.MockServletConfig.class org.springframework.mock.web.MockServletContext.class org.springframework.mock.web.PassThroughFilterChain.class org.springframework.mock.web.portlet.MockActionRequest.class org.springframework.mock.web.portlet.MockActionResponse.class org.springframework.mock.web.portlet.MockMultipartActionRequest.class org.springframework.mock.web.portlet.MockPortalContext.class org.springframework.mock.web.portlet.MockPortletConfig.class org.springframework.mock.web.portlet.MockPortletContext.class org.springframework.mock.web.portlet.MockPortletPreferences.class org.springframework.mock.web.portlet.MockPortletRequest.class org.springframework.mock.web.portlet.MockPortletRequestDispatcher.class org.springframework.mock.web.portlet.MockPortletResponse.class org.springframework.mock.web.portlet.MockPortletSession.class org.springframework.mock.web.portlet.MockPortletURL.class org.springframework.mock.web.portlet.MockRenderRequest.class org.springframework.mock.web.portlet.MockRenderResponse.class org.springframework.test.AbstractDependencyInjectionSpringContextTests.class org.springframework.test.AbstractSingleSpringContextTests.class org.springframework.test.AbstractSpringContextTests.class org.springframework.test.AbstractTransactionalDataSourceSpringContextTests.class org.springframework.test.AbstractTransactionalSpringContextTests.class org.springframework.test.AssertThrows.class org.springframework.test.ConditionalTestCase.class org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.class org.springframework.test.annotation.DirtiesContext.class org.springframework.test.annotation.ExpectedException.class org.springframework.test.annotation.IfProfileValue.class org.springframework.test.annotation.NotTransactional.class org.springframework.test.annotation.ProfileValueSource.class org.springframework.test.annotation.Repeat.class org.springframework.test.annotation.SystemProfileValueSource.class org.springframework.test.annotation.Timed.class org.springframework.test.jpa.AbstractAspectjJpaTests.class org.springframework.test.jpa.AbstractJpaTests.class org.springframework.test.jpa.OrmXmlOverridingShadowingClassLoader.class org.springframework.test.web.AbstractModelAndViewTests.class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值