SpringBoot之单元测试(打包测试)=>Junit

测试环境

  1. jdk1.8

  2. springboot  2.0.4.RELEASE

  3. idea 2018

1.pom

        
        
            org.springframework.boot
            spring-boot-starter-test
            
            test
        

2.项目结构

SpringBoot之单元测试(打包测试)=>Junit_第1张图片

3.测试类

import com.zzq.po.UserInfo;
import com.zzq.service.UserInfoService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
// web 项目的时候,这里可以模拟ServletContext,加上 WebAppConfiguration 就可以实现
@WebAppConfiguration
public class GetAllTest {

    @Autowired
    private UserInfoService userInfoService;

    @Before
    public void init(){
        System.out.println("=============================> 测试开始了...");
    }

    @Test
    public void getAll(){
        List userInfos = userInfoService.getAll();
        for (UserInfo info: userInfos) {
            System.out.println( info );
        }
    }

    @After
    public void after(){
        System.out.println("=============================> 测试结束了...");
    }

}

SpringBoot之单元测试(打包测试)=>Junit_第2张图片

4.当有多个测试类的时候,可以写一个 BaseAppTest , 然后其他的类继承该类,就不用 每个类都加注解了。

就像这样:

@RunWith(SpringRunner.class)
@SpringBootTest
// web 项目的时候,这里可以模拟ServletContext,加上 WebAppConfiguration 就可以实现
@WebAppConfiguration
public class BaseAppTest {

    @Before
    public void before(){
        System.out.println("开始测试===========================>");
    }

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

}
public class GetAll extends BaseAppTest {

    @Autowired
    private UserInfoService userInfoService;

    @Test
    public void getAll(){
        List userInfos = userInfoService.getAll();
        for (UserInfo info: userInfos) {
            System.out.println( info );
        }
    }

    @Ignore("不需要测试的可以使用 Ignore 注解标明不需要测试")
    @Test
    public void testSiute(){
        System.out.println("=================>这个方法用来测试忽略方法<====================");
    }

}

5.打包测试

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * 打包测试
 */
@RunWith(Suite.class)
@Suite.SuiteClasses(value = {GetAll.class,InsertUser.class})
public class SuiteTest {


}

使用 @Suite.SuiteClasses 注解,里面填写需要测试的类。

如果某个类里面有暂时不需要测试的方法,则使用 @Ignore注解标识。value 里面写不需要测试的原因,可以不写。

6.打包测试运行效果:

SpringBoot之单元测试(打包测试)=>Junit_第3张图片

 

参考博客:https://blog.csdn.net/weixin_39800144/article/details/79241620,感谢大佬分享。

你可能感兴趣的:(springboot,SpringBoot菜鸟教程)