解决:The import org.springframework.test.context.junit4.SpringJUnit4ClassRunner cannot be resolved

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/menggudaoke/article/details/53192274

近期自己在自家新电脑上搭建了Eclipse + Maven环境,然后在做单元测试的时候,创建Spring测试类,在为测试类添加@RunWith(SpringJUnit4ClassRunner.class)注解的时候,遇到了这个问题:The import org.springframework.test.context.junit4.SpringJUnit4ClassRunner cannot be resolved,百度搜索了国内的多个网站,都是Shit的不行,全TM的复制粘贴,十个网站都是同一个问题,同一个答案,同一个标点符号。

根本原因是SpringJUnit4ClassRunner这个类是位于spring-test-4.1.6.RELEASE.jar这个包中的,其他人只谈Junit却根本没提到这一点,所以才导致根本找不到正确的答案。

经过在Stackoverflow上面查找答案,看到了第一个回答之后,瞬间感觉一语中的。原文地址:http://stackoverflow.com/questions/30513375/the-import-org-springframework-test-context-junit4-springjunit4classrunner-canno



6down voteaccepted

You need to add a dependency on spring-boot-starter-test:

<dependency><!--这里是spring-boot的解决办法-->
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
shareimprove this answer
 
 
Thanks! this solved my problem. – Juan Carlos May 28 '15 at 17:49 
 
I had to add also the version but worked also for me – Aditzu Sep 21 at 10:45
 
@aditzu If you are using Spring Boot, then adding the version should not be needed. – Wim Deblauwe Sep 21 at 13:32
 
这里是使用spring时遇到此问题的解决办法:You are right. For me which I'm not using Spring Boot, a dependency for "spring-test" was the solution. Thanks! – Aditzu Sep 21 at 13:56
注意我标注的绿色的回复,是使用spring而不是使用spring-boot的解决方式,即在自己的pom.xml中添加如下依赖:
 

   <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>4.1.6.RELEASE</version>
  </dependency>
加上这个依赖之后,等maven把jar包下载下来之后,问题就解决了。

还有人回复说跟junit版本有关的,如果本地的junit版本较低,也请你在pom.xml中增加一下新版本的junit依赖,如下:

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

6down voteaccepted

You need to add a dependency on spring-boot-starter-test:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
shareimprove this answer
 
 
Thanks! this solved my problem. – Juan Carlos May 28 '15 at 17:49 
 
I had to add also the version but worked also for me – Aditzu Sep 21 at 10:45
 
@aditzu If you are using Spring Boot, then adding the version should not be needed. – Wim Deblauwe Sep 21 at 13:32
 
You are right. For me which I'm not using Spring Boot, a dependency for "spring-test" was the solution. Thanks! – Aditzu Sep 21 at 13:56
阅读更多
换一批

没有更多推荐了,返回首页