首页 技术 正文
技术 2022年11月21日
0 收藏 425 点赞 2,930 浏览 1331 个字

今天在看Spring的Demo的时候,看到了如此单元测试的写法

如下:

@RunWIth(SpringJunit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:applicationContext.xml"}public  class MyTest{@Test
public void hehe()
{
//.......
}
}

这种写法是为了让测试在Spring容器环境下执行。

Spring的容器环境是啥呢?

比如常见的 Service Dao Action , 这些个东西,都在Spring容器里,junit需要将他们拿到,并且使用来测试。

好,笔者写一个十分简单的demo让大家有个体会!

显示demo的项目结构

@RunWith和 SpringJUnit4ClassRunner —->junit4和Spring一起使用

要写的东西就两个: applicationContext.xml 和MyTest.java
applicationContext.xml 中仅仅只定义了一个Date对象。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean name="date" class="java.util.Date"/> </beans>

@RunWith和 SpringJUnit4ClassRunner —->junit4和Spring一起使用

接下来是MyTest.java的内容

 import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource;
import java.util.Date; /**
* Created by HuLuo on 2016/8/19.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MyTest
{
@Resource
Date date; @Test
public void hehe()
{
System.out.println(date.toLocaleString());
}
}

@RunWith和 SpringJUnit4ClassRunner —->junit4和Spring一起使用

最后只需要运行就可以了。

@RunWith和 SpringJUnit4ClassRunner —->junit4和Spring一起使用

最后如图所示,成功拿到了Spring容器里的Date对象。

诸如哪些 Action Service Dao ServiceImpl DaoImpl都是一个道理,可以通过这种方式拿到,然后进行单元测试。。。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,023
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,361
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,143
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,774
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,853