0
点赞
收藏
分享

微信扫一扫

springboot测试的两种方式

1、controller类的代码

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String hello() {
return "hello world!";
}
}

2、测试类的代码,包含引入的类

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.request.MockMvcRequestBuilders;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


// 第一种方式,推荐这种使用更方便
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc

// 第二种方式@WebMvcTest中的参数需要填你要测试的controller类,而不是Application.class
//@RunWith(SpringRunner.class)
//@WebMvcTest(HelloController.class)
public class HelloControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("hello world!")));
}
}

举报

相关推荐

0 条评论