SpringBoot项目整合使用Junit单元测试

一:首先项目pom文件引入junit的依赖


            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            

二:添加test文件夹目录,路径跟项目目录保持一致

SpringBoot项目整合使用Junit单元测试_第1张图片

 

三:创建一个junit测试基类

SpringBoot项目整合使用Junit单元测试_第2张图片

import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StreamTestApplication.class) //设置springboot启动类
@WebAppConfiguration//由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
class StreamApplicationTests {

    @Before
    public void init() {
        System.out.println("junit开始测试-----------------");
    }

    @After
    public void after() {
        System.out.println("junit测试结束-----------------");
    }


}

 

四:写要测试的测试功能类,继承上面的junit测试基类就行,不用再配复杂的注解

public class SglTest extends StreamApplicationTests{
    @Autowired
    private LoveStarServiceImpl loveStarService;

    @Test
    public void testGetMyFavoriteStar(){
        Assert.assertSame("最喜欢的球星错误!","kobe1",loveStarService.getMyFavoriteStar());
    }

    @Test
    public void testGetKobeTopScore(){
        Assert.assertSame("kobe最高分错误!",81,loveStarService.getKobeTopScore());
    }

}

LoveStarServiceImpl 是你要测试的具体service

本例子测试了LoveStarServiceImpl  的  getMyFavoriteStar getKobeTopScore 这两个方法

可以看下我这两个方法的正确返回值:

SpringBoot项目整合使用Junit单元测试_第3张图片

应该是kobe 和 81。

测试类里面的:

Assert.assertSame() 是junit提供的校验方法

参数意义:

第一个参数:如果测试不通过,会抛出此消息,此参数可不要;

第二个参数:我预期的值,我这里希望他查出来的结果是kobe1;

第三个参数:是实际的结果,就是我们调用方法返回的结(service返回的结果是kobe);

然后就会抛出错误提示:

SpringBoot项目整合使用Junit单元测试_第4张图片

如果期望值与方法返回值相同,说明方法没问题,则不会有任何错误提示!

 

五:打包测试

四只是举了一个例子测试一个service,但是工作中业务复杂肯定有很多业务service方法需要去测试,就不能一个个的去测试,浪费时间效率低,我们可以打包测试

SpringBoot项目整合使用Junit单元测试_第5张图片

我这里建了两个测试类,分别是SglTest,SglTest2,现在我打包进TestSuits,让他们一次运行:

@RunWith(Suite.class)
@Suite.SuiteClasses({SglTest.class,SglTest2.class})

用这两个注解实现!

/**
 * @Description: 打包测试
 * @Author: sgl
 * @Date: 2020/7/22 0022 下午 19:55
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({SglTest.class,SglTest2.class})
public class TestSuits {
    //不用写代码,只需要注解即可
}

然后之间运行TestSuits就可以打包测试所有的测试类了

SpringBoot项目整合使用Junit单元测试_第6张图片

没问题的service会通过,不满足的则会抛出问题!

 

六:忽略某个测试方法

@Ignore("not ready yet")

在测试类的方法上面加 @Ignore注解就可以

SpringBoot项目整合使用Junit单元测试_第7张图片

 

SpringBoot项目整合使用Junit单元测试_第8张图片

被忽略的方法不会进行junit测试!

 

你可能感兴趣的:(我自己的学习笔记,Spring框架)