UnfinishedVerificationException
是在使用 Mockito 进行单元测试时可能遇到的一种异常。这个异常通常表示你在验证某个方法调用时没有正确地完成验证过程。具体来说,当你使用 Mockito.verify()
方法来验证某个方法是否被调用时,如果没有正确地指定验证的条件或者验证的逻辑不完整,就会抛出这个异常。
Mockito: 是一个流行的 Java 测试框架,用于进行单元测试,特别是用于模拟对象的行为。
Verification: 在单元测试中,验证是指检查某个方法是否按照预期被调用。
UnfinishedVerificationException: 当 Mockito 无法完成验证过程时抛出的异常,通常是因为验证条件不完整或不正确。
类型:
应用场景:
假设我们有以下类和方法需要测试:
public class ExampleService {
public void doSomething(String param) {
if (param == null) {
throw new IllegalArgumentException("Parameter cannot be null");
}
// 其他逻辑
}
}
在测试中,我们可能会这样写:
import static org.mockito.Mockito.*;
import org.junit.Test;
public class ExampleServiceTest {
@Test(expected = IllegalArgumentException.class)
public void testDoSomethingWithNullParam() {
ExampleService service = mock(ExampleService.class);
service.doSomething(null);
}
@Test
public void testDoSomethingVerification() {
ExampleService service = mock(ExampleService.class);
service.doSomething("validParam");
// 这里会抛出 UnfinishedVerificationException
verify(service).doSomething(isNull());
}
}
在上述代码中,testDoSomethingVerification
方法会抛出 UnfinishedVerificationException
,因为我们在验证时使用了 isNull()
,但实际调用时传递的是 "validParam"
,这导致了验证失败。
解决方法:
@Test
public void testDoSomethingVerification() {
ExampleService service = mock(ExampleService.class);
service.doSomething("validParam");
// 正确的验证应该是检查方法是否被调用,而不是参数是否为 null
verify(service).doSomething(anyString());
}
any()
或 anyString()
等匹配器: 如果你不关心具体的参数值,可以使用这些通配符匹配器。@Test
public void testDoSomethingVerification() {
ExampleService service = mock(ExampleService.class);
service.doSomething("validParam");
verify(service).doSomething(anyString());
}
通过这种方式,你可以确保验证逻辑正确完成,避免 UnfinishedVerificationException
的发生。
领取专属 10元无门槛券
手把手带您无忧上云