在Spring的框架下,单元测试方法。
- 手动加载Spring的配置文件,并启动Spring容器
- 使用Spring中对Junit框架的整合功能
前提:
除了Junit4和Spring的jar包,还需要spring-test.jar
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
方法一:
- 注解加载配置文件
private AreaService service;
protected ApplicationContext context;
@Before
public void init(){
//context = new FileSystemXmlApplicationContext( new String[]{"classpath:applicationContext.xml" ,"classpath:mybatis-config.xml"});
context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
service = (AreaService) context.getBean("areaService");
}
@Test
public void Test(){
service.query();
}
- 静态代码块加载配置文件
private AreaService service;
//静态代码块加载
static{
//context = new FileSystemXmlApplicationContext("applicationContext.xml");
//context = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml","classpath:/spring/application*.xml"});
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
service = (AreaService) context.getBean("areaService");
}
//main方法执行测试
@SuppressWarnings("resource")
public static void main(String[] args) {
try {
service.do();
} catch (BizException e){
e.printStackTrace();
}
}
- main函数中执行spring的代码
脱离Tomcat容器在单独的java application的main函数中初始化spring
public static void main(String[] args){
//手动加载spring的配置文件,并启动spring容器
/*GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.setValidating(false);
context.load("classpath*:applicationContext*.xml");
context.refresh();*/
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//context.start();
ReadDao fqa = (ReadDao) context.getBean("readDao");
fqa.do();
}
方法二:全注解
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration需要配上spring的配置文件,这样就可以在测试类中使用注解简单的注入需要的bean了。简单高效。
@ContextConfiguration({"classpath:applicationContext.xml"})
public class ReadDaoImplTest{
@Autowired
private AreaService areaService;
@Resource
private ReadDao readDao;
@Test
public void test(){
areaService.query();
}
@Test
public void getListTest(){
List<Client> clientList = readDao.getList("client.test",null);
for(Client c:clientList){
System.out.println(c.getVersionNum());
try {
// 断言:判断z==6,
assertEquals(6, z);
//断言:判断z<3
assertTrue(z<3);
} catch (BizException e) {
e.printStackTrace();
}
}
}
}
解释下用到的注解:
@RunWith:用于指定junit运行环境
@ContextConfiguration:用于指定spring配置环境
@TransactionConfiguration:用于配置事务
@Transactional表示所有类下所有方法都使用事务