当在使用 JUnit 进行单元测试时,如果在调用 when(...).thenReturn(...)
方法时遇到 NullPointerException
,通常是因为 Mockito 框架无法找到要模拟的对象或方法。以下是一些基础概念和相关解决方案:
null
时抛出的异常。when(...).thenReturn(...)
之前,必须先创建并注入模拟对象。import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ExampleTest {
@Mock
private Dependency dependency;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testMethod() {
when(dependency.someMethod()).thenReturn("mockedValue");
// 进行测试
}
}
确保 when(...).thenReturn(...)
中的方法名和参数类型与实际的方法一致。
when(dependency.someMethod(arg1, arg2)).thenReturn("expectedResult");
如果需要模拟静态方法或私有方法,可以使用 PowerMockito。
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@ExtendWith(MockitoExtension.class)
@PrepareForTest(StaticClass.class)
public class StaticMethodTest {
@Test
public void testStaticMethod() {
PowerMockito.mockStatic(StaticClass.class);
when(StaticClass.staticMethod()).thenReturn("mockedValue");
// 进行测试
}
}
通过上述方法,可以有效解决在使用 JUnit 和 Mockito 进行单元测试时遇到的 NullPointerException
问题。确保正确初始化和使用模拟对象是关键步骤。
领取专属 10元无门槛券
手把手带您无忧上云