• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot Controller Post接口单元测试示例

springboot 搞代码 4年前 (2022-01-05) 24次浏览 已收录 0个评论

今天小编就为大家分享一篇关于SpringBoot Controller Post接口单元测试示例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

概述

在日常的开发中,我们一般会定义一个service层,用于实现业务逻辑,并且针对service层会有与之对应的齐全的覆盖率高的单元测试。而对于controller层,一般不怎么做单元测试,因为主要的核心业务逻辑都在service层里,controller层只是做转发,调用service层接口而已。但是还是建议使用单元测试简单的将controller的方法跑一下,看看转发和数据转换的代码是否能正常工作。

Spring Boot里对controller层进行单元测试非常简单,只需要几个注解和一点点辅助代码即可搞定。

依赖的包

  org.junit.jupiterjunit-jupiter-apitest org.junit.jupiterjunit-jupiter-enginetest org.springframework.bootspring-boot-starter-testtest com.alibabafastjson

使用的Spring Boot 版本

2.0.4.RELEASE

代码

 @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment<p style="color:transparent">来源gao!%daima.com搞$代*!码网</p>.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 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 Object test(@RequestBody(required = false)User user) throws Exception { }

如果你只是想简单的跑一下controller层,不想真正的去执行service方法的话,需要使用@MockBean将对应的servicemock掉。

 @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)

经过测试,如上代码能正常工作。

总结

以上就是SpringBoot Controller Post接口单元测试示例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot Controller Post接口单元测试示例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址