Springboot单元测试,使用mvc访问Controller

1.构建单元测试类步骤

  1. 对需要进行测试的类alt+enter,创建test类
  2. 在类上添加注解

    @RunWith(SpringRunner.class)   //在spring环境中运行  在使用所有注释前必须使用@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境

    @SpringBootTest(classes = PersonaPortalApplication.class)  //其中,classes属性指定启动类,SpringBootTest.WebEnvironment.RANDOM_PORT经常和测试类中@LocalServerPort一起在注入属性时使用。会随机生成一个端口号。

    @AutoConfigureMockMvc @AutoConfigureMockMvc是用于自动配置MockMvc

  3.  自动装配 Mockmvc
  4. 在需要测试的方法里写入测试方法
  5. 创建RequestBuilder对象,封装 url 参数和参数类型 
    ex:
    RequestBuilder request = get("/tagdev/listTags")
    
                    .param("tagId","5")
    
                    .contentType(MediaType.APPLICATION_JSON_UTF8);

     

 

      6.使用MockMvc对象发送请求 获得返回结果

2.test例子

package com.**

import com.**
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;

import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

/**
 * @author zhaozheng
 * @create 2019/2/14
 **/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ‘自己的springboot启动类’.class)
@AutoConfigureMockMvc
public class TagDevControllerTest {
    @Autowired
    private MockMvc mvc;
    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void addTag() {
    }

    @Test
    public void updateTag() {
    }

    @Test
    public void listTag() throws Exception {
        RequestBuilder request = get("Controller的url路径:去除application中的server.servlet.context-path=/**")
                .param("tagId","5")
                .contentType(MediaType.APPLICATION_JSON_UTF8);
        String contentAsString = mvc.perform(request).andReturn().getResponse().getContentAsString();
        System.out.println(contentAsString);

    }

    @Test
    public void exportExcel() {
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值