spring-test+JUnit达成springMVC测试脚本转载

原创
小哥 3年前 (2022-11-11) 阅读数 3 #大杂烩

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

1、加入jar包:

junit junit 3.8.1 test org.springframework spring-test 4.0.6.RELEASE

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("新的成功!");

}
}
从上面可以看出,在测试类中测试要测试的代码是简单而方便的。


作者:星空中的王牌
来源:CSDN
原文:https://blog.csdn.net/xingkongdeasi/article/details/79963827
版权声明:本文为博主原创文章。转载请附上博客链接!

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除