您的位置:首页 > 编程语言 > Java开发

junit+spring Test.jar 单元测试

2016-08-29 16:30 399 查看
本文转自:隆回水哥一文

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<
aa98
/span>" })
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  junit spring 单元测试