SpringBoot @Test单元测试

待我称王封你为后i 2023-02-18 15:21 132阅读 0赞

一、普通测试

  1. 初步了解:springboot一般使用maven搭建工程,在maven工程中存在test包(虽然测试用例是可以存在于src下,但是规范统一是放在test中),我们的在test包可以同步src下的包结构,针对相应的java类写test用例,在做单元测试这是非常重要的
  2. 一个简单的测试用例,就像main方法一样

    1. public class UtilTest {
    2. @Test
    3. public void currencyTest() throws Exception{
    4. String uuid = MD5Util.getMd5("测试用例");
    5. System.out.println(uuid);
    6. }
    7. }

    注意到这里我们使用了这个注解@Test,由JUnit提供,它回去扫描带有该注解的方法去调用,从而达到相对应的效果

二、SpringBoot调用测试

  1. 我们调用springboot中的controller、service、mapper层时,需要注入它们,需要springboot的相关环境
  2. 测试用例:

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = SpringBootCatApplication.class)
    public class CatTest {
    @Autowired
    private ElasticDao elasticDao;
    @Autowired
    private testService testService;

    @Test
    public void testEs() throws Exception{

    1. ResponseEntity responseEntity = elasticDao.saveAndUpdateBulkList(EsIndexEnum.TEST.type,"test","test");
    2. System.out.println(responseEntity);

    }

    @Test
    public void testTestService() throws Exception{

    1. ResultEntity ResultEntity = testService.test("1");
    2. System.out.println(ResultEntity);

    }
    }

这里我们添加了两个注解@RunWith@SpringBootTest,可以进入SpringBootTest中查看到这一段代码确认web环境,一般我们将classes指向启动类

  1. SpringBootTest.WebEnvironment webEnvironment() default SpringBootTest.WebEnvironment.MOCK;

三、Junit4单元测试

这个依赖于idea的插件Junit

  1. 1、选择要测试的java
  2. 2、按住alt+insert
  3. 3、选择Junit Test
  4. 4、选择Junit4
  5. 5、生成在test对应包下

测试内容可以选择上述直接调用方法体,也可以是用Junit提供的Mock对象

  1. /**
  2. * 模拟mvc测试对象
  3. */
  4. private MockMvc mockMvc;
  5. /**
  6. * web项目上下文
  7. */
  8. @Autowired
  9. private WebApplicationContext webApplicationContext;
  10. /**
  11. * 所有测试方法执行之前执行该方法
  12. */
  13. @Before
  14. public void before() {
  15. //获取mock对象
  16. mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  17. }

比较测试结果是否符合预期可以使用

  1. Assert.assertEquals("预期结果", "实际结果");
  2. Assert.assertTrue();
  3. Assert.assertNotNull();
  4. Assert.assertNotEquals();
  5. Assert.assertNull();

我们可以使用Jacoco,来获得我们单元测试的分支覆盖率,这里我就不做过多的描述了,有兴趣可以去了解一下

四、pom.xml依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-test</artifactId>
  9. <version>2.1.3.RELEASE</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>junit</groupId>
  13. <artifactId>junit</artifactId>
  14. <version>4.12</version>
  15. </dependency>

发表评论

表情:
评论列表 (有 0 条评论,132人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot单元测试

    1、SpringBoot单元测试 单元测试(Unit Test)是为了检验程序的正确性。一个单元可能是单个程序、类、对象、方法等,它是应用程序的最小可测试部件。Sprin