概述
在日常的开发中,我们一般会定义一个service层,用于实现业务逻辑,并且针对service层会有与之对应的齐全的覆盖率高的单元测试。而对于controller层,一般不怎么做单元测试,因为主要的核心业务逻辑都在service层里,controller层只是做转发,调用service层接口而已。但是还是建议使用单元测试简单的将controller的方法跑一下,看看转发和数据转换的代码是否能正常工作。
在Spring Boot里对controller层进行单元测试非常简单,只需要几个注解和一点点辅助代码即可搞定。
依赖的包
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spring work.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
使用的Spring Boot 版本
2.0.4.RELEASE
代码
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.MOCK,classes = TestApplication.class)
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
@DisplayName(\"测试controller方法\")
void test() throws Exception {
User param = new User();
param.setUserId(1111);
List<Address> addressList = new ArrayList<>();
Address address = new Address();
address.setName(\"我的地址\");
addressList.add(address);
param.setAddressList(addressList);
MvcResult mvcResult = mockMvc.perform(
post(\"/xxx/test\")
.contentType(MediaType.APPLICATION_JSON)
.content(JSON.toJSONString(param)))
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
}
@RequestMapping(value = \"/xxx\", method = RequestMethod.POST)
public test(@RequestBody(required = false)User user) throws Exception {
}
如果你只是想简单的跑一下controller层,不想真正的去执行service方法的话,需要使用@MockBean将对应的service类mock掉。
@MockBean private UserService userService;
使用Spring Boot Test的时候,它需要一个ApplicationContext,我们可以在@SpringBootTest注解中使用classes属性来指定。
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.MOCK,classes = TestApplication.class)
TestApplication的代码很简单。
@SpringBootApplication
public class TestApplication {
public static void main(String[] args){
SpringApplicationBuilder builder = new SpringApplicationBuilder();
builder.environment(new StandardEnvironment());
builder.sources(TestApplication.class);
builder.main(TestApplication.class);
builder.run(args);
}
}
接下来我们只需要使用MockMvc发送post请求即可。如果controller层的post方法是带@RequestBody注解的,可以先将入参对象转换成JSON字符串。这里使用的是fastjson。
JSON.toJSONString(param)
经过测试,如上代码能正常工作。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接
继续阅读与本文标签相同的文章
上一篇 :
姚期智:量子计算机进入“最后一里路”
下一篇 :
易语言整数型参数传递详解
-
NEXT创新大会走进合肥,看“新经济”带“科创之都”腾飞。
2026-05-19栏目: 教程
-
win7系统想要用iis7远程桌面管理,可是他显示说你没有开通远程权限怎么解决?
2026-05-19栏目: 教程
-
好程序员大数据学习路线分享MapReduce全流程总结
2026-05-19栏目: 教程
-
什么是高防?有什么用?
2026-05-19栏目: 教程
-
阿里云如何添加CDN解析过程 新手必看教程
2026-05-19栏目: 教程
