service层的单元测试(springboot)

2020-06-26  本文已影响0人  侧耳倾听y
  1. pom依赖

有以下依赖即可

<dependency>
  <groupId>org.springframework.boot</groupId>  
  <artifactId>spring-boot-starter-test</artifactId>
</dependency>
  1. 文件夹层次

保证test文件夹下,与main文件夹下的结构是一样:

3.把web模块的配置,移植到service模块的test

项目中的配置文件和启动类,一般都在web模块下,但是我们需要在service层跑单元测试,那么就需要把这些东西给service模块复制一份。
先复制配置文件:

配置文件
配置文件搞定之后,需要在service模块的pom文件,加下以下内容,确保单元测试跑的时候,可以读取配置文件:
接下来复制启动类,放在test下根目录即可:
  1. 编写测试类基类
这里编写一个测试类基类,以后有其他功能的测试类,都可以继承这个类:

代码:

package com.example.service;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplication.class)
public class AbstractContextServiceTest   {


}

  1. 编写功能测试类

注意,测试类包名要与被测试类完全一致:



代码:

package com.example.service.test;

import com.example.pojo.TestPojo;
import com.example.service.AbstractContextServiceTest;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.junit.jupiter.api.Assertions.*;

class TestServiceTest extends AbstractContextServiceTest {

    @Autowired
    private TestService testService;

    @Test
    void getTestData() {
        TestPojo testData = testService.getTestData();
        Assert.assertEquals("北京 is a busy city", testData.getTestData());
    }
}
  1. 运行测试类

点击Run with Coverage选项,可以看下单侧的覆盖率:


单测通过,绿色代表覆盖到的代码:
上一篇 下一篇

猜你喜欢

热点阅读