0%

Spring中使用JUnit4的过度方法

肯定有整合过的单元测试组件用,spring不会有这么不优雅的东西,只是我还不会,暂时凑合着先用 ORZ

  • 创建UnitTestBase类(放在Test目录好看点),完成对Spring配置文件的加载、销毁所有的单元测试类都继承自UnitTestBase,通过它的getBean方法获取想要得到的对象

  • 子类(具体执行单元测试的类)加注解:

    @RunWith(BlockJUnit4ClassRunner.class)

  • 单元测试方法加注解:@Test

  • 右键选择要执行的单元测试方法执行或者执行一个类的全部单元测试方法

UnitTestBase工具类

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.***;

import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

public class UnitTestBase {

private ClassPathXmlApplicationContext context;

private String springXmlpath;

public UnitTestBase() {}

public UnitTestBase(String springXmlpath) {
this.springXmlpath = springXmlpath;
}

@Before
public void before() {
if (StringUtils.isEmpty(springXmlpath)) {
springXmlpath = "classpath*:spring-*.xml";
}
try {
context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
context.start();
} catch (BeansException e) {
e.printStackTrace();
}
}

@After
public void after() {
context.destroy();
}

@SuppressWarnings("unchecked")
protected <T extends Object> T getBean(String beanId) {
try {
return (T)context.getBean(beanId);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
}

protected <T extends Object> T getBean(Class<T> clazz) {
try {
return context.getBean(clazz);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
}
}