【问题标题】:Can not run Junit in eclipse无法在 Eclipse 中运行 Junit
【发布时间】:2021-12-01 19:30:26
【问题描述】:

我正在尝试使用以下代码运行 spring boot crud 示例

@SpringBootTest @RunWith(MockitoJUnitRunner.class)

公共类 CreateUserServiceTest {

@Mock
private UserRepository userRepository;

@InjectMocks
private CreateUserService createUserService;

@Test
public void whenSaveUser_shouldReturnUser() {
    User user = new User();
    user.setName("Test Name");

    when(userRepository.save(ArgumentMatchers.any(User.class))).thenReturn(user);

    User created = createUserService.createNewUser(user);

    assertThat(created.getName()).isSameAs(user.getName());
    verify(userRepository).save(user);
}

}

但运行后出现以下错误。

“没有找到测试运行器'junit5'的测试”

请大家帮帮我。

Please check the error message from this file.

【问题讨论】:

  • 请提供错误信息。
  • 看起来测试没有编译...

标签: spring junit


【解决方案1】:

编辑:我找到了根本原因。

JUnit 5 使用来自与 JUnit 4 不同的包中的注解。当您开始测试时,Eclipse 会自动为 JUnit 5 创建启动配置,但如果您的注解不在新包中,Eclipse 将找不到测试并会显示错误信息。

New annotations:

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
// ... other imports from org.junit.jupiter.api

旧注释:

import org.junit.Test;
// ... imports without "jupiter" in their name

您需要在 Maven 项目中添加以下依赖项才能使用 JUnit 5:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <scope>test</scope>
</dependency>

解决方法:使用 JUnit 4。 您需要在启动配置中选择 JUnit 4。否则会显示此错误。

从主菜单中选择运行 -> 运行配置,然后从左侧导航栏中选择您的 JUnit 测试配置。

【讨论】:

  • 按照您的指示运行后。现在不能用了
  • 发生了什么?你又收到错误信息了吗? In my IDE I have never been able to run tests when JUnit 5 is selected.更改为 JUnit 4 对我有用。
  • 是的,谢谢,选择 junit4 后,它正在工作。
  • 不错!如果您觉得答案有帮助,请投票。 ;)
  • 在有帮助的答案的左侧有一个 V 标志,您可以单击并表示答案解决了您的问题。
猜你喜欢
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 2017-11-21
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
  • 2012-06-02
相关资源
最近更新 更多