Spring测试用例自动注入Bean(下)

文章目录
  1. 1. 方案一:使用 Junit 测试框架
    1. 1.1. 依赖
    2. 1.2. 实现
  2. 2. 方案二:使用 Mockito 测试框架
    1. 2.1. 依赖
    2. 2.2. 实现

如果Bean的初始化是通过 xml 进行的,可以参考文章:Spring测试用例自动注入Bean(上),下面讲到的是「在没有 xml配置文件时,如何测试诸如 @Component @Service @Repository 等注解标识的类」。

待测试的类,注意该 Bean 有一个 init() 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class DemoService {

/* 初始化逻辑*/
@PostConstruct
public void init() {
// initialization code
}

public void printName() {
System.out.println("I'm Yves");
}
}

方案一:使用 Junit 测试框架

依赖
1
2
3
4
5
6
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = {com.yves.service.DemoService.class})
@DirtiesContext
public class DemoServiceTest {

@Autowired
private DemoService demoService;

@Test
public void testPrintName() {
demoService.printName();
}
}

@ContextConfiguration 注解中,需要传入一个 ClassLoader 和待测试的类,所以我们也可以简单推测下:通过这样的注解,Junit 可以通过加载指定的 Class 文件,帮我们完成注入。

@DirtiesContext 注解表明底层 Spring 容器在该方法的执行中被“污染”,从而必须在方法执行结束后重新创建(无论该测试是否通过)。

顺便提一句:@ContextConfiguration 里还有一个 locations 属性,我们可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件。如下所示:
@ContextConfiguration(locations={“xx/beans1.xml”,” yy/beans2.xml”})

方案二:使用 Mockito 测试框架

依赖
1
2
3
4
5
6
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RunWith(MockitoJUnitRunner.class)
public class DemoServiceTest {

@InjectMocks
private DemoService demoService;

@Before
public void setup() {
this.demoService.init();
}

@Test
public void testPrintName() {
demoService.printName();
}
}

需要注意的是:在 DemoService 中,通过 @PostConstruct 注解的初始化方法需要手动调用,原因是 @PostConstruct 是 Spring 框架下的注解。所以使用 mockito 进行 注解测试还是有些 ugly,推荐使用 Junit