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

spring中用JUnit做单元测试时多个spring配置文件的引入

2018-01-29 22:41 387 查看


这是我项目的结构图,可以看到将spring配置文件拆分成了若干个xml文件。这是在web.xml中的引入:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>然后在maven的pom.xml中引入JUnit和spring-test的jar包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.2.RELEASE</version>
<scope>test</scope>
</dependency>然后再test文件夹中创建单元测试类
package TestMybatis;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.hyit.oj.mapper.UsersMapper;
import cn.hyit.oj.pojo.Users;
import cn.hyit.oj.pojo.UsersExample;
import cn.hyit.oj.pojo.UsersExample.Criteria;

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:spring/applicationContext*.xml"})
public class test {
@Autowired
UsersMapper usersMapper;
@Test
public void testInsertUser(){
Users record = new Users();
record.setUserId("guxiang1234");
usersMapper.insertSelective(record);
}

@Test
public void testSelectUsersById(){
UsersExample usersExample = new UsersExample();
Criteria criteria = usersExample.createCriteria();
criteria.andUserIdEqualTo("1151317109");
List<Users> users = usersMapper.selectByExample(usersExample);
System.out.println(users.get(0).getNick());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/applicationContext*.xml"})
打上上面两行注解即可,表示使用spring环境运行junit以及加载spring文件夹下以applicationContext开头的xml文件,*是通配符。
好了之后可以看到spring容器已经起作用,将usersMapper的实现类给注入进来了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  junit 单元测试