一、基本测试方法

1 junit方式

1.1 所需依赖

  1. <!--SpringBoot的测试类-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-test</artifactId>
  5. <scope>test</scope>
  6. </dependency>
  7. <!--junit-->
  8. <dependency>
  9. <groupId>junit</groupId>
  10. <artifactId>junit</artifactId>
  11. <version>4.12</version>
  12. <scope>test</scope>
  13. </dependency>

1.2 代码示例

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 springboot.test.aop.UserService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootBaseApplication.class)
public class TestAOP {

    @Autowired
    private UserService userService;

    @Test
    public void test1(){
        int m = userService.reg();
        System.out.println(m);
    }
}

2 纯SpringBoot【不推荐】

2.1 所需依赖

<!--SpringBoot的测试类-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2.2 代码示例

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import springboot.test.aop.UserService;


@SpringBootTest
public class TestAOP2 {

    @Autowired
    private UserService userService;

    @Test
    public void test1(){
        int m = userService.reg();
        System.out.println(m);
    }
}

2.3 原因

在正常情况下测试类是需要@RunWith的,作用是告诉java你这个类通过用什么运行环境运行,例如启动和创建spring的应用上下文。否则你需要为此在启动时写一堆的环境配置代码。你在IDEA里去掉@RunWith仍然能跑是因为在IDEA里识别为一个JUNIT的运行环境,相当于就是一个自识别的RUNWITH环境配置。但在其他IDE里并没有。