1.使用JUnit做单元测试加载Spring的XML配置文件#

1.1 问题简介#

在学习Spring的XML配置过程中,希望能够在单元测试时直接引入XML文件,但是如下的单元测试代码报错:

1
java.io.FileNotFoundException: class path resource [spring-context.xml] cannot be opened because it does not exist

对应的项目目录结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[2020-02-22 20:48.27]  /drives/i/个人/博客管理/Github/Spring/spring/spring-XMLcomponent/src
[qhc.DESKTOP-IDDQ7KK] ➤ tree
.
+--- main
| +--- java
| | +--- com
| | | +--- qhc
| | | | +--- xml
| | | | | +--- Disc.java
| | | | | +--- DiscDriver.java
| +--- resources
| | +--- spring-context.xml
+--- test
| +--- java
| | +--- XMLTest.java

XMLTest.java文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import com.qhc.xml.DiscDriver;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("spring-context.xml") //本意是想直接饮用resources目录下的spring-context.xml文件
public class XMLTest {
@Autowired
private DiscDriver discDriver;

@Test
public void xmlTest(){
discDriver.paly();
}

}

但是执行上面的测试代码后提示:

1
2
3
4
5
	... 24 more
Caused by: java.io.FileNotFoundException: class path resource [spring-context.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 36 more

这就很令我迷惑,还跟着网上的帖子设置了IntelliJ IDEA 之 mark directory as(),都试过了也没起作用,也是自己不断的尝试,终于被我发现了正确的引入xml的方式。

1.2 正确引入方式#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import com.qhc.xml.DiscDriver;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
//方式一:
//@ContextConfiguration(locations="classpath:spring-context.xml") 这里这两种写法都是可以的

//方式二:
@ContextConfiguration("/spring-context.xml")
public class XMLTest {
@Autowired
private DiscDriver discDriver;

@Test
public void xmlTest(){
discDriver.paly();
}

}

上面的两种方式都是可以的。

  • 方式一:@ContextConfiguration(locations=”classpath:spring-context.xml”)
  • 方式二:@ContextConfiguration(“/spring-context.xml”)

以下这是我遇到的错误方式

  • 错误方式一:@ContextConfiguration(“spring-context.xml”) 我怀疑告诉spring的路径中识别不到这个文件,具体我还不知道怎么取论证。