1. 程式人生 > >SpringBoot之單元測試

SpringBoot之單元測試

MockMvc實現了對Http請求的模擬,能夠直接使用網路的形式,轉換到Controller的呼叫,這樣可以使得測試速度快、不依賴網路環境,而且提供了一套驗證的工具,這樣可以使得請求的驗證統一而且很方便。

controller

@RestController
public class IndexController {

    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}

測試controller

package com.xxx.demo.controller;
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.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.abc.demo.controller.IndexController;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=IndexController.class)
@AutoConfigureMockMvc
public class IndexControllerTest {
	@Autowired
	private MockMvc mockMvc;
	
	//初始化操作
	@Before
	public void setUp(){
		mockMvc=MockMvcBuilders.standaloneSetup(new IndexController()).build();
	}
	@Test
	public void index() throws Exception{
		mockMvc.perform(MockMvcRequestBuilders.get("/index")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk());
	}
}
推薦文章:https://blog.csdn.net/vqhgWJl9EUB/article/details/78930280