spring-junit 的使用

  1. 导入 pom 依赖
1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.6</version>
</dependency>
  1. 使用
    1. 导入@Runwith
    2. 导入 ContextConfiguration
    3. 配置需要的注解 例如 @Autowired
    4. 配置测试方法 @Test (这个很重要 , 如果没有配置调用方法会报错的)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.yuelin.service;

import com.ithema.config.SpringConfig;
import com.ithema.domain.Power;
import com.ithema.service.PowerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class PowerServiceTest {
@Autowired
private PowerService powerService;

@Test
public void getAll() {
List<Power> all = powerService.findAll();
System.out.println(all);
}
}