在我们平时的测试中,完成一个功能,都需要单元测试,接口的话,可以通过浏览器或者postman进行接口测试, 有时开发job类功能或者只调整部分代码,junit单元测试就很方便了,接下来简单介绍下。

1、引入基础依赖

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

2、创建测试service类

  1. import org.springframework.stereotype.Service;
  2. @Service
  3. public class UserService {
  4. public String getUser() {
  5. return "cola";
  6. }
  7. }


3、创建spring的配置类applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  7. <!-- 配置组件包扫描的位置 -->
  8. <context:component-scan base-package="org.lee.junit"/>
  9. </beans>

4、test包下新建Junit测试类

  1. @RunWith(SpringRunner.class)
  2. @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
  3. public class UserServiceTest {
  4. @Autowired
  5. private UserService userService;
  6. @Test
  7. public void test() {
  8. System.out.println(userService.getUser());
  9. }
  10. }

注意:如果使用的spring版本小于4.3, 需要使用:

  1. @RunWith(SpringJUnit4ClassRunner.class)

上面的方法是通过xml配置文件的方式,还可以使用Java Config的方式:

新建配置类SpringConfig

  1. import org.springframework.context.annotation.ComponentScan;
  2. @ComponentScan(basePackages = "org.lee.architect.junit")
  3. public class SpringConfig {
  4. }

测试用例中使用如下注解:

  1. @ContextConfiguration(classes = {SpringConfig.class})

在 SpringBoot 中
由于 @RunWith和@ContextConfiguration 都是可继承的
项目中如果单元测试用例较多,我们可以写个基础测试类BaseTest,然后其他的测试用例继承BaseTest,就可以省略了

  1. @RunWith(SpringRunner.class)
  2. @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
  3. public class BaseTest {
  4. }
  5. // UserServiceTest就可以这样写了:
  6. public class UserServiceTest extends BaseTest {
  7. @Autowired
  8. private UserService userService;
  9. @Test
  10. public void test() {
  11. System.out.println(userService.getUser());
  12. }
  13. }

2、Ngari

基本上本地测试都是通过配置vm options里的属性设置后,在启动。

但我们平时会遇到需要测试的接口不是很庞大的情况, 这就会遇到启动整个资源浪费的情况,
其实我们可以进行单元测试 对一个模块进行调试。
首先看到
image.png
consult项目为例,
image.png

  1. @RunWith(SpringRunner.class)

JUnit运行使用Spring的测试支持。SpringRunner是SpringJUnit4ClassRunner的新名字,这样做的目的
仅仅是为了让名字看起来更简单一点。

在当前的文件下配置
image.png

测试完成