【发布时间】: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