首页 > 技术文章 > 【SSM】SSM学习笔记(5):解决Maven项目不能使用spring单元测试注解@ContextConfiguration的问题

northwest332 2020-11-24 17:08 原文

问题描述:

已经在pom.xml中导入了spring单元测试模块:

		<!-- spring的单元测试模块 -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.7.RELEASE</version>
			<scope>test</scope>
		</dependency>

但是还是不能使用spring单元测试注@ContextConfiguration:

image.png

解决办法:

删除这一行:

<scope>test</scope>

所以是这样:

		<!-- spring的单元测试模块 -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.7.RELEASE</version>
		</dependency>

问题解决。

错误原因:

这是scope依赖作用域的问题。

<scope>test</scope>

这一行表示,依赖仅在测试范围有效,在编译和打包时都不使用这个依赖。

Maven的scope依赖作用域说明

1、test范围指的是测试范围有效,在编译和打包时都不会使用这个依赖

2、compile范围指的是编译范围有效,在编译和打包时都会将依赖存储进去

3、provided依赖:在编译和测试的过程有效,最后生成war包时不会加入,诸如:servlet-api,因为servlet-api,tomcat等web服务器已经存在了,如果再打包会冲突

4、runtime在运行的时候依赖,在编译的时候不依赖

默认的依赖范围是compile

关于scope依赖作用域的内容请参考这里

推荐阅读