springboot 单元测试报错

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

在单元测试时,报错如下:

The import org.springframework.test.context.junit4.SpringRunner cannot be resolved

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {
}

大概说的是SpringRunner这个类找不到

我的项目描述:

pom文件里面

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.0.5.RELEASE</version>
    <scope>test</scope>
</dependency>

我的解决办法:把<artifactId>spring-test</artifactId>这个依赖去掉就好了

为什么?网上偶然看到,说可能spring-boot-starter-test已经包括了spring-test和junit了。

我们看一下依赖,

(先把pom文件中的spring-test和junit依赖注释掉)在eclipse 里面,选中项目,Run as -> maven build...命令行执行 dependency:tree

点击Run运行,结果:

好像确实是这么回事。

那既然包含关系,我想应该是覆盖了,为啥会报错,仔细看我的pom文件,好像版本不对。我的springboot 默认继承父类的版本1.5.7,而spring-test是4.0.5.RELEASE,应该是版本冲突,所以解决办法有两个,要么只去掉这个<version>4.0.5.RELEASE</version>标签,要么去掉这个spring-test依赖。

猜你喜欢

转载自blog.csdn.net/baofengyu90/article/details/86500016