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

Spring + Spring MVC + mybatis 下的 junit4 注入单元测试

2017-01-01 15:14 405 查看
spring环境下的JUnit4测试

1.下载所需jar包:

spring-test-4.0.2.RELEASE.jar

junit-4.11.jar

Maven

<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.11</version>
<scope>test</scope>
</dependency>


以上2个包必须加入spring-test.jar集成了spring测试环境,缺了包不能正常注入。一般测试注入不成功应该是缺这包导致。junit 测试包尽可能应用高点版本,我所应用的是4.11版

@RunWith(SpringJUnit4ClassRunner.class)
 


让测试运行于Spring测试环境Spring框架在
org.springframework.test.annotation
 包中提供了常用的Spring特定的注解集,如果你在Java5或以上版本开发,可以在测试中使用它

@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})  

locations:可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件。如下所示:
@ContextConfiguration(locations={“spring1.xml”,”spring2.xml”}),locations路径为在classes文件夹下或Maven resources下,q且配置文件下路径用classpath:指定,否则特殊情况下识别路径有误。
inheritLocations:是否要继承父测试用例类中的 Spring 配置文件,默认为 true。
若写classpath*:spring-mvc.xml 和 classpath*:spring-mybatis.xml代表所有资源文件遍历,首先会查main资源,之后查找test资源

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})
public class cTest {

@Autowired
public AdminService adminService;

@Test
public void test() {

Admin a = new Admin();
a.setUsername("user");
a.setPassword("sds");
adminService.insertSelective(a);
}

}


总结不好多多担待,文章只单纯个人总结,如不好勿喷,技术有限,有错漏麻烦指正提出。本人QQ:373965070
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息