1.添加测试需要依赖的jar包
注意版本,junit的版本最好不要低于spring-test的版本,还有就是spring-test的版本与其他spring的版本注意不要冲突
<!--Junit测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
以上两个包是必须要引入的,特别是spring-test的jar包,不引入就无法在测试文件中使用@RunWith等注解
2.编写测试文件
package com.test.service.impl;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.test.pojo.User;
import com.test.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/spring-mybaits.xml"})
public class UserServiceImplTest {
@Autowired
private static UserService userService;
@BeforeClass
public static void init() {//junit之前init spring
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-mybaits.xml");
userService = (UserService)context.getBean("userServiceImpl");
}
@Test
public void testGetUserById() {
User user=this.userService.getUserById(1);
System.out.println("-----------------------");
System.out.println(user);
System.out.println("-----------------------");
}
}
代码解释:
1.@RunWith(SpringJUnit4ClassRunner.class)
- 让测试运行于Spring测试环境,Spring框架在
org.springframework.test.annotation
包中提供了常用的Spring特定的注解集,如果你在Java5或以上版本开发,可以在测试中使用它
2.@ContextConfiguration(locations={"classpath:spring/spring-mybaits.xml"})
locations:可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件。如:@ContextConfiguration(locations={“spring1.xml”,”spring2.xml”}),locations路径为在classes文件夹下或Maven resources下,q且配置文件下路径用classpath:指定,否则特殊情况下识别路径有误。
若写classpath*:spring-mvc.xml 和 classpath*:spring-mybatis.xml代表所有资源文件遍历,首先会查main资源,之后查找test资源
3.@BeforeClass
由于junit运行单个文件的时候并没启动容器,也就无法进行实例化,使用service,那么@autowrid注解就是无效的。所以要在注入service之前执行init()方法,对该service进行实例化才能调用其中的方法。