SpringBoot @Test单元测试
一、普通测试
- 初步了解:springboot一般使用maven搭建工程,在maven工程中存在test包(虽然测试用例是可以存在于src下,但是规范统一是放在test中),我们的在test包可以同步src下的包结构,针对相应的java类写test用例,在做单元测试这是非常重要的
- 一个简单的测试用例,就像main方法一样 public class UtilTest { @Test public void currencyTest() throws Exception{ String uuid = MD5Util.getMd5("测试用例"); System.out.println(uuid); } } 注意到这里我们使用了这个注解@Test,由JUnit提供,它回去扫描带有该注解的方法去调用,从而达到相对应的效果
二、SpringBoot调用测试
- 我们调用springboot中的controller、service、mapper层时,需要注入它们,需要springboot的相关环境
- 测试用例:
@RunWith(SpringRunner.class) @SpringBootTest(classes = SpringBootCatApplication.class) public class CatTest { @Autowired private ElasticDao elasticDao; @Autowired private testService testService; @Test public void testEs() throws Exception{ ResponseEntity responseEntity = elasticDao.saveAndUpdateBulkList(EsIndexEnum.TEST.type,"test","test"); System.out.println(responseEntity); } @Test public void testTestService() throws Exception{ ResultEntity ResultEntity = testService.test("1"); System.out.println(ResultEntity); } }
这里我们添加了两个注解@RunWith和@SpringBootTest,可以进入SpringBootTest中查看到这一段代码确认web环境,一般我们将classes指向启动类
SpringBootTest.WebEnvironment webEnvironment() default SpringBootTest.WebEnvironment.MOCK;
三、Junit4单元测试
这个依赖于idea的插件Junit
1、选择要测试的java类 2、按住alt+insert键 3、选择Junit Test 4、选择Junit4 5、生成在test对应包下
测试内容可以选择上述直接调用方法体,也可以是用Junit提供的Mock对象
/** * 模拟mvc测试对象 */ private MockMvc mockMvc; /** * web项目上下文 */ @Autowired private WebApplicationContext webApplicationContext; /** * 所有测试方法执行之前执行该方法 */ @Before public void before() { //获取mock对象 mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); }
比较测试结果是否符合预期可以使用
Assert.assertEquals("预期结果", "实际结果"); Assert.assertTrue(); Assert.assertNotNull(); Assert.assertNotEquals(); Assert.assertNull();
我们可以使用Jacoco,来获得我们单元测试的分支覆盖率,这里我就不做过多的描述了,有兴趣可以去了解一下
四、pom.xml依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> <version>2.1.3.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
上一篇:
Python 安装包管理工具 pip
下一篇:
接口文档以及接口测试用例