spring-test+JUnit实现springMVC测试用例

        利用spring-test与JUnit来测试代码能给我们带来很多便利,所以简单写一篇spring-test与JUnit的测试实例

1、加入jar包:

<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.0.6.RELEASE</version>
		</dependency>

2、创建spring-test的基类,该类主要用来加载配置文件,设置web环境的,然后所有的测试类继承该类即可,基类BaseTest类代码如下:

package com.jjx.controller;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml","classpath:spring-mybatis.xml"})
@WebAppConfiguration("src/main/webapp")			
public class BaseTest {

}

@RunWith(SpringJUnit4ClassRunner.class) 使用junit4进行测试

@ContextConfiguration() 加载spring相关的配置文件
@WebAppConfiguration() 设置web项目的环境,如果是Web项目,必须配置该属性,否则无法获取 web 容器相关的信息(request、context 等信息)


3、测试类,测试类只要继承上面的基类BaseTest即可,代码如下:

public class Mytest extends BaseTest {

	@Resource       // 自动注入
	private EmpService empService;
	
	@Test
	public void test01() {
		System.out.println(empService.getById(5000).getEname());
	}
	
	@Test
	public void addCompletEmpInfo() {
		// 员工入职日期
		Date hiredate = new Date(new java.util.Date().getTime());
		// 新增加的部门信息
		Dept dept = new Dept(55, "临时部门", "地址不详");
		// 新增加的员工信息
		Emp emp = new Emp(7500, "路人甲", "临时工", 5000, 
				hiredate, new BigDecimal(2000), new BigDecimal(100), dept);
		// 新增员工信息及对应的部门信息插入数据中
		empService.addCompleteEmp(emp);
		
		System.out.println("新增成功!");
		
	}
}
        从上面可以看到,这样在测试类中就可以测试程序中想要测试的代码,简单方便。

猜你喜欢

转载自blog.csdn.net/xingkongdeasi/article/details/79963827