单元测试二、对controller层
程序员文章站
2022-03-02 18:06:25
...
1.加入pom依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2.在application.properties加入扫描文件
<context:component-scan base-package="com.junittestdemo.demo" />
3. 编写controller的类
package com.junittestdemo.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* package:com.junittestdemo.demo.controller
*
* @date:2020/4/16 17:20
* @author:Yaoxiaoming
**/
@RestController
public class StudentContoller {
@RequestMapping("/hello")
public String Helloworld(){
return "hello king";
}
}
4.编写controller测试类
package com.junittestdemo.demo.controller;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
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.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
/**
* package:com.junittestdemo.demo.controller
*
* @date:2020/4/17 8:37
* @author:Yaoxiaoming
**/
@SpringBootTest
class StudentContollerTest {
//mock对象
private MockMvc mockMvc;
@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new StudentContoller()).build();
}
@Test
void helloworld() {
try {
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.request(HttpMethod.GET, "/hello"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print())
.andReturn();;
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.运行以后,就可以访问hello world了
上一篇: 自己在平时项目中所使用到的JS代码
下一篇: Java 项目所用到的基础API (1)
推荐阅读
-
Spring Boot从Controller层进行单元测试的实现
-
ASP.NET Core对Controller进行单元测试的完整步骤
-
spring boot使用自定义注解+AOP实现对Controller层方法的日志记录
-
利用单元测试在每个层上对PHP代码进行检查(1)_PHP教程
-
python大展身手带你通过罩层对彩图进行二值化操作,实现抠图与图像拼接
-
对Angular.js Controller如何进行单元测试
-
数值微分版 对MNIST数据集的二层神经网络的学习实现
-
误差反向传播法版 对MNIST数据集的二层神经网络的学习实现
-
利用单元测试在每个层上对PHP代码进行检查(1)
-
对Angular.js Controller如何进行单元测试