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("新增成功!");
        
    }
}
        从上面可以看到,这样在测试类中就可以测试程序中想要测试的代码,简单方便。
--------------------- 
作者:星空的阿斯 
来源:CSDN 
原文:https://blog.csdn.net/xingkongdeasi/article/details/79963827 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值