IntelliJ中,junit @RunWith未解决。

12

我有以下测试代码:

package soundSystem;

import static org.junit.Assert.*;

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(classes = CDPlayerConfig.class)

public class SonyCDPlayerTest {

@Autowired
private ICompactDisk cd;

@Test
public void cdShouldNotBeNull() {
    assertNotNull(cd);
}

}

这是一个Maven项目,问题是相同的代码可以在Eclipse中运行,但不能在Intellij中运行。我找不到解决@RunWith的方法。

screen shot from intellij

2个回答

35
@RunWith注解在JUnit 5.0及以上版本(最新的Spring版本正在使用)中已被替换为@ExtendWith注解。

示例:


@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringTest {
    // ...
}

引用自Baeldung:

请注意,SpringExtension.class由Spring 5提供,并将Spring TestContext框架集成到JUnit 5中。

参考资料:https://www.baeldung.com/junit-5-runwith


8

简单来说:你的IDE没有配置单元测试。

换句话说:你缺少所有与JUnit相关的类。你可以看到所有那些JUnit导入都被下划线标记了;因为IntelliJ不知道包含相应类的JAR文件。

请参考这里以了解如何修复。


非常感谢,我一整个下午都在解决这个问题,之前我不知道我应该在我的项目结构中添加jar文件,但我仍然不明白为什么当我的Maven pom文件中有JUnit,项目结构中有Maven:JUnit时,我还需要手动添加它。 - Z.better
那部分我不能告诉你 ;-( - GhostCat
谢谢大家一样,:-) - Z.better
1
后来我发现是因为我的本地Maven仓库中的JUnit包已经损坏了,重新下载后一切正常。 - Z.better
很高兴你最终找到了真正的问题! - GhostCat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接