![446d347d3d17923644234e1064cdea21.png](https://i-blog.csdnimg.cn/blog_migrate/8dfb7a03efe721786d74b3e1dae3ec69.jpeg)
为什么要使用Assertions断言呢?
- 表达式上更加直观和清晰;
- 提升代码的可读性;
- 测试代码变得更加容易维护
引入依赖:
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.2.RELEASE'testCompile group: 'org.assertj', name: 'assertj-core', version: '3.11.1'
Assertions断言的运用:
@RunWith(SpringRunner.class)@WebAppConfiguration@SpringBootTest@Transactional@Sql("classpath:/sql/admin/dynamicCode/updateDynamicCodeTests.sql")public class UpdateDynamicCodeTests extends BaseDynamicCodeControllerTests { @Autowired private DynamicCodeService dynamicCodeService; /** * 动态码更新-正常态 */ @Test public void updateDynamicCodeSuccessfully() throws Exception { Long id = LongUtil.toLong(1); // 更新前的动态码信息 DynamicCodeResponse originalDynamicCode = dynamicCodeService.getDynamicCodeInfo(id); String responseContent = mMockMvc.perform( MockMvcRequestBuilders.put(BASE_HOST + "/api/admin/dynamic/code/" + id) .contentType(MediaType.APPLICATION_JSON_UTF8) .sessionAttr(AUTHORIZED_ATTRIBUTE_NAME, getAuthSession())) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn().getResponse().getContentAsString(); prettyPrintJson(responseContent); //assert response JsonNode jsonNode = mObjectMapper.readTree(responseContent); // 更新成功后的动态码信息 DynamicCodeResponse dynamicCode = jsonNode.get("data").traverse(mObjectMapper).readValueAs(DynamicCodeResponse.class); Assertions.assertThat(originalDynamicCode).isNotEqualTo(null); Assertions.assertThat(dynamicCode).isNotEqualTo(originalDynamicCode);Assertions.assertThat(dynamicCode.getActive()).isEqualTo(originalDynamicCode.getActive());Assertions.assertThat(dynamicCode.getPlanId()).isEqualTo(originalDynamicCode.getPlanId());Assertions.assertThat(dynamicCode.getCode()).isNotEqualTo(originalDynamicCode.getCode());Assertions.assertThat(dynamicCode.getIsSub()).isEqualTo(originalDynamicCode.getIsSub()); Assertions.assertThat(dynamicCode.getId()).isEqualTo(originalDynamicCode.getId()); }}
![7cb2eb21796fef5c042acac25cb8b9d8.png](https://i-blog.csdnimg.cn/blog_migrate/dca4660b055c7b86cb850cff9c46aa78.jpeg)
最后,对测试类上标注的5个注解进行解释说明:
- @RunWith(SpringRunner.class) 表明单元测试运行借助于SpringRunner 驱动器
- @WebAppConfiguration 表明这是一个Web类型的单元测试,即Controller级别的Tests
- @SpringBootTest 表明这是一个Spring Boot 项目的单元测试
- @Transactional 事务回滚
- @Sql("classpath:/sql/admin/dynamicCode/updateDynamicCodeTests.sql") 单元测试的数据准备,建议每个table的insert操作前,都使用 truncate table tableName; 将数据清空,以免发生主键冲突等状况。建议连接本地MySQL数据库进行单元测试!
![f1988623f198607e318123ee0606324c.png](https://i-blog.csdnimg.cn/blog_migrate/1d441f08d884c8f98801a174c00d3008.jpeg)