junit4 spring集成测试
很多时候我看见小伙伴这样测试spring的service或者dao,每个类后面写个main,使用new方式加载spring配置文件,获取需要测试的实例,然后对实例进行测试。稍微好一点的在junit测试类里面new加载spring配置文件进行测试。其实junit测试spring可以很方便的进行。这里会用到spring-test-xxx.jar,junit4的jar。 其中要注意的是:@RunWith(SpringJUnit4ClassRunner.class)1、如果spring配置文件applicationContext.xml在classpath路径下,即通常的src目录下,这样加载配置文件,用classpath前缀。@ContextConfiguration(locations = { "classpath:applicationContext.xml" })2、但是在web项目中,有些人喜欢把spring配置文件applicationContext.xml放在WEB-INF目录下,这里不是classpath目录。这种情况可以按如下方式配置:用file前缀,指定配置文件的绝对路径。貌似这种方式不是很友好。@ContextConfiguration(locations = { "file:F:\\workspace\\web-test\\src\\main\\resources\\"
+ "applicationContext.xml" })spring配置文件applicationContext.xml:<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.wss.lsl.junit.demo" />
</beans>待测试的service,就一个方法,求两个整数的和。package com.wss.lsl.junit.demo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class CalculateService {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 计算:返回两个整数的和
*
* @param first
* @param second
* @return
*/
public int sum(int first, int second) {
logger.info("求和参数:first={}, second={}", first, second);
return first + second;
}
}测试基类,所有其他的测试类集成此类,从而无需再重复配置加载spring配置文件。package com.wss.lsl.junit.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class BaseTest {
@Test
public void _() {
}
}测试类如下,我们可以很方便把要测试的实例@Autowired进来,这样优雅多了。package com.wss.lsl.junit.demo.service;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.wss.lsl.junit.demo.BaseTest;
public class CalculateServiceTest extends BaseTest {
@Autowired
private CalculateService calculateService;
@Test
public void testSum() {
int expected = 5, first = 3, second = 2;
int real = calculateService.sum(first, second);
// 验证
assertEquals(expected, real);
}
}
页:
[1]