赞
踩
目录
在日常开发的过程中,对自己的代码进行单元测试是个非常重要的过程,一方面可以最小范围的针对一个方法进行测试,提高测试的简便性以及测试的成本,不用启动这个项目。另一方面,做好单元测试能降低代码的BUG率。本篇文章主要是为了总结一下如何优雅的在Springboot项目中使用单元测试去测试功能。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
如果使用的开发工具为IntelliJ IDEA,点击进入方法,鼠标右键
点击Generate然后选择Test
选择好之后点击Ok就创建好一个测试类了。
然后在测试类上添加@SpringBootTest注解,需要测试的方法上已经有@Test注解了 。点击方法左侧的三角形即可运行单元测试方法。
Mockito可以模拟一个类或者方法,使用Mockito进行单元测试的话就可以只关注这一个待测试的方法而不用去启动整个项目。项目依赖很多环境,比如中间件、数据库等,如果使用第一种方法进行测试的话,则这些环境都要准备好。
了解完了Mockito常使用的一些注解之后,下面就开始对各种情况的Mock
- @SpringBootTest
- public class ProductImageServiceImplMockito {
-
- @Mock
- private ProductImageMapper productImageMapper;
-
- @InjectMocks
- private ProductImageServiceImpl productImageService;
-
-
- @BeforeEach
- public void setup() {
- MockitoAnnotations.openMocks(this);
- }
-
-
- @Test
- public void testGet() {
- ProductImage productImage = new ProductImage();
- productImage.setId(1l);
- productImage.setImageUrl("mockUrl");
- // mock方法的逻辑
- when(productImageMapper.selectById(1l)).thenReturn(productImage);
- ProductImage image = productImageService.getByImageId(1l);
- assertEquals("mockUrl", image.getImageUrl());
- }
- }

在Mapper上面添加了@Mock注解,则Mapper中的方法都是mock的,这里mock了selectById方法。
- // Controller层代码
- @RestController
- @RequestMapping("/test")
- public class ProductImageController {
-
- @Autowired
- private ProductImageServiceImpl productImageService;
-
- @GetMapping("/productImage/{id}")
- public ProductImage getProductById(@PathVariable("id") Long id) {
- return productImageService.getByImageId(id);
- }
- }
-
- // 测试方法代码
- @WebMvcTest(ProductImageController.class)
- public class ProductImageServiceImplMockitoV2 {
-
- @MockBean
- private ProductImageServiceImpl productImageService;
-
- @Autowired
- private MockMvc mockMvc;
-
- @Test
- public void test() throws Exception {
- ProductImage productImage = new ProductImage();
- productImage.setId(1l);
- productImage.setImageUrl("mockUrl");
- when(productImageService.getByImageId(1l)).thenReturn(productImage);
- MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/productImage/1"))
- .andExpect(status().isOk())
- .andReturn();
- String contentAsString = mvcResult.getResponse().getContentAsString();
- }
- }

直接模拟发送http请求到Controller的API接口,并调用@MockBean中mock出来的方法
还有很多场景,这里就不一一列举了,直接参考大神文章《在Spring Boot环境中使用Mockito进行单元测试》
本文介绍了一些单元测试的方法,在日常开发中应该避免使用main方法测试的方式进行测试,因为main方法既无法模拟项目的环境,而且又受静态方法的影响只能调用静态方法。还有一些其它的测试工具,录入yapi、easymock等也可以进行测试使用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。