springboot测试类编写

编写springboot测试类

依赖

		
			org.springframework.boot
			spring-boot-starter-test
			test
		

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;


@Transactional //测试后数据h会回滚
@WebAppConfiguration
@SpringBootTest
@RunWith(SpringRunner.class)
public class RequestAPITest {
    
    private MockMvc mvc;
    
    @Autowired
    WebApplicationContext webContext;
   
    @org.junit.Before
    public void before(){
        mvc = MockMvcBuilders.webAppContextSetup(webContext).build();
    }
    
    @Test
    public void test() throws Exception {

        //请求头
        HttpHeaders headers = new HttpHeaders();
        //请求参数
        MultiValueMap params = new LinkedMultiValueMap();
        //请求URI
        String uri = "/person/get";
        
        headers.add("head", "");
        
        params.add("age", "10");
        
        MvcResult result = mvc.perform(
                //MockMvcRequestBuilders.post(uri)
                MockMvcRequestBuilders.get(uri)
                .headers(headers)
                .params(params)
            .accept(MediaType.APPLICATION_JSON_UTF8)
        ).andReturn();

        
        int status = result.getResponse().getStatus(); //获取执行结果的状态
        String content= result.getResponse().getContentAsString(); //获取响应内容

        System.out.println("返回结果 "+ status + "  "+ content);
        
        Assert.assertEquals("错误", 200,status);
       
    }   

}

/*
mvc.perform(
        MockMvcRequestBuilders.get(uri)
        .headers(headers)
        .params(params)
    .accept(MediaType.APPLICATION_JSON_UTF8)
).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(equalTo("")));
*/

 

你可能感兴趣的:(SpringBoot)