@RunWith(SpringJUnit4ClassRunner.class)使用

概述

对于集成Spring的Java程序,想写相关的单元测试,可以用到它:

@RunWith(SpringJUnit4ClassRunner.class)

作用:
使用junit写单元测试时,方便从Spring容器中取得对象。

一般还会结合下面的内容使用,指定Spring xml配置文件,例子如下:

@ContextConfiguration(locations = ("/test/appContext.xml"))
或者
@ContextConfiguration(locations ={“classpath:/test/appContext.xml”})

配置

如果是maven项目,需要在pom.xml文件中添加依赖,例子如下:

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

注意:
因为我使用的是4.3.21.RELEASE的版本,如果junit对应的版本低于4.12,就会报下面的错误信息,所以我这边配置的是4.12的版本。

*Caused by: java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher. at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:102) ... 14 more*

版权声明:本文为weixin_44728363原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。