Spring项目Junit测试
Spring项目Junit测试
1.引入测试所需的依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2.测试Controller、Service方法
测试类上添加注解
@RunWith(SpringRunner.class)
@SpringBootTest
测试方法上添加注解
@Test
示例
测试包下的测试类
package com.guigu.test;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest
class TestApplicationTests {
@Autowired
ShowController showController;
private MockMvc mockMvc; // 专门模拟浏览器发出各种请求
@Test
public void update() throws Exception{
mockMvc = MockMvcBuilders.standaloneSetup(showController).build();
RequestBuilder getRequest = MockMvcRequestBuilders.post("/aaa/bbb/ccc")
.param("a","a");
//获取结果和返回值
MvcResult result = mockMvc.perform(getRequest).andReturn();
MockHttpServletResponse response = result.getResponse();
//输出响应结果
System.out.println("响应结果:"+response.getContentAsString());
System.out.println("状态码:"+response.getStatus());
}
}
被测试的Controller
package com.guigu.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @Description TODO
* @Author
* @Date 2022/4/20
* @Version 1.0
*/
@Controller
@RequestMapping("/aaa")
public class ShowController {
@Autowired
private ShowService showService;
@RequestMapping("/bbb/ccc")
public String test(@RequestParam String a) {
System.out.println("ShowController"+a);
return showService.show();
}
}
被测试的Service
package com.guigu.test;
import org.springframework.stereotype.Service;
/**
* @Description TODO
* @Author
* @Date 2022/4/20
* @Version 1.0
*/
@Service
public class ShowService {
public String show(){
System.out.println("xxx");
return "x";
}
}