本文转自:隆回水哥一文
junit测试spring可以很方便的进行,这里需要用到spring-test-xxx.jar,junit4的jar。
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测试:
@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 _() {
}
}
其中要注意的是:
@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" })
测试类如下,可以很方便把要测试的实例@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);
}
}