Spring boot JUnit4->;JUnit5,服务单元测试代码不工作
Spring启动版本:2.1.6 JUnit依赖项版本:5.3.2(更高版本不可用(不工作)) 格雷德尔先生Spring boot JUnit4->;JUnit5,服务单元测试代码不工作,spring-boot,junit,junit5,spring-boot-test,Spring Boot,Junit,Junit5,Spring Boot Test,Spring启动版本:2.1.6 JUnit依赖项版本:5.3.2(更高版本不可用(不工作)) 格雷德尔先生 dependency { testImplementation("org.springframework.boot:spring-boot-starter-test") { exclude module: 'junit' } testRuntimeOnly("org.junit.platform:junit-plat
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测试代码运行良好。
Bit服务层单元测试不工作
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存储库是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);
}
}
在JUnit4代码段中,@Mock注释字段被初始化,因为您正在用MockitoRule加载Mockito。Mockito负责创建模拟,并将它们分配给@Mock注释字段 但是JUnit 5不支持以下规则: 在JUnit5测试类中,@Rule注释的MockitoRule字段被忽略,因此不会加载Mockito,也不会分配@Mock注释的字段
要在JUnit 5测试类中加载Mockito,请删除MockitoRule,改为使用@extendedwith(MockitoExtension.class)注释该类。“规则”是JUnit 4机制。您必须将其替换为Jupiter扩展。使用
@extendedwith(MockitoExtension.class)
而不是MockitoRule
。多亏了你,我解决了这个问题。!!!!