【问题标题】:JUnit4 -> JUnit5, service unit test code does not workJUnit4 -> JUnit5,服务单元测试代码不起作用
【发布时间】:2021-08-05 18:22:48
【问题描述】:

Spring Boot 版本:2.1.6 JUnit 依赖版本:5.3.2(更高版本不可用(不工作))

build.gradle

dependency {
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude module: 'junit'
    }

    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
    testRuntimeOnly("org.junit-vintage:junit-vintage-engine")
    testImplementation("org.junit.jupiter:junit-jupiter-api")
    testImplementation("org.junit.platform:junit-platform-runner)
}

其他常见的 JUnit5 测试代码运行良好。 位服务层单元测试不工作。

JUnit4 测试代码:效果很好

import org.junit.Test;
// ....

public class SomeServiceUnitTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @InjectMock
    SomeServiceImpl someService;

    @Mock
    SomeRepository someRepository;

    @Test
    public void somethingTestForSuccess() {
        // GIVEN
        when(someRepository.getSomething("abc")).thenReturn(100);

        // WHEN 
        boolean result = someService.doSomething("testObject");

        // THEN 
        assertTure(result);
    }

}

但是,JUnit5 : Mock Repository 是 NullPointException

import org.junit.jupiter.api.Test;
// ....

class SomeServiceUnitTest {

    @Rule
    MockitoRule mockitoRule = MockitoJUnit.rule();

    @InjectMock
    SomeServiceImpl someService;

    @Mock
    SomeRepository someRepository;

    @Test
    void somethingTestForSuccess() {
        // GIVEN
        when(someRepository.getSomething("abc")).thenReturn(100);

        // WHEN 
        boolean result = someService.doSomething("testObject");

        // THEN 
        assertTure(result);
    }

}

【问题讨论】:

  • “规则”是一种 JUnit 4 机制。您必须将其替换为木星扩展。
  • 在您的测试中使用@ExtendWith(MockitoExtension.class) 而不是MockitoRule

标签: spring-boot junit junit5 spring-boot-test


【解决方案1】:

在您的 JUnit 4 代码 sn-p 中,@Mock 注释字段已初始化,因为您正在使用 MockitoRule 加载 Mockito。 Mockito 负责创建模拟并将它们分配给 @Mock 注释字段。

但是 JUnit 5 不支持规则:

https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4-rule-support

在您的 JUnit 5 测试类中,@Rule 注释的 MockitoRule 字段被忽略,因此未加载 Mockito 并且未分配 @Mock 注释的字段。

要在您的 JUnit 5 测试类中加载 Mockito,请删除 MockitoRule 并使用 @ExtendWith(MockitoExtension.class) 注释该类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    相关资源
    最近更新 更多