使用spring boot和spring test mock mvc单元测试junit4集成

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Melody_Susan/article/details/86214668

spring boot使用单元测试需要使用@SpringBootTest,@RunWith(SpringRunner.class)注解,如果需要使用mock mvc还需要增加@AutoConfigureMockMvc注解,这里的spring boot版本是2.0以下的,SpringBootTest注解,默认不设置是不会启动整个服务测试的,使用的是mock环境策略。下面演示的例子是启动tomcat服务策略进行整个服务测试。

package com.xxx.bizaccount.test;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.xxx.SpringBootStarter;
import com.xxx.bizaccount.model.BizaccountVO;
import xxx.JSONObject;

/**
 * 费用报销单测试类
 * 
 * @author 许畅
 * @since JDK1.7
 * @version 2019年1月3日 许畅 新建
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = { SpringBootStarter.class })
@AutoConfigureMockMvc
public class TestBizAccount {
    
    @Autowired
    private MockMvc mockMvc;
     
    /**
     * 业务单据更新测试
     * 
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception {
        BizaccountVO testData = new BizaccountVO();
        testData.setName("许畅测试");
        testData.setNumber("测试编号");
        testData.setAmount(111.00);
        this.mockMvc
            .perform(put("/bizaccount/update").contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(JSONObject.toJSONString(testData)).accept(MediaType.ALL))
            .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andDo(print());
    }
    
    @Override
    protected MockMvc getMockMvc() {
        return mockMvc;
    }
}

 这里只是写个例子更多资料可自行查看对应的官网版本资料学习。

猜你喜欢

转载自blog.csdn.net/Melody_Susan/article/details/86214668