【发布时间】:2023-02-01 23:25:31
【问题描述】:
我有一个 A 类,它有一个 methodA 在 B 类中调用一个 methodB。
在 B 类中 methodB 正在调用 C 类中的 methodC。
C 类实现methodC。
我正在尝试使用 junit、mockito 在 A 类中测试 methodA。
@ExtendWith(MockitoExtension.class)
public class ClassATest {
@Mock
APIGatewayProxyRequestEvent event;
@Mock
Context context;
@Spy
@InjectMocks
ClassB classB;
@Spy
@InjectMocks
ClassA classA;
@Test
@DisplayName("everything should pass")
public void testMethodA() throws Exception {
Person p = new Person("xyz", "abc", 12345, true);
when(classB.methodB(any(Molecule.class), eq("abc"), eq(12345), eq(null))).thenReturn(p);
Map<String, String> headerMap = new HashMap<>();
headerMap.put("id", "12345");
when(event.getHeaders()).thenReturn(headerMap);
when(event.getBody()).thenReturn("{name:hello}");
assertEquals(classA.methodA(event, context).getStatusCode(), 500);
}
我收到类 C methodC 的空指针异常错误。我也需要嘲笑它吗?有没有办法我可以模拟methodB,以便测试确实回复methodB 中的实现?因为我的目标是测试methodA,所以我可以模拟其他方法。
【问题讨论】:
标签: java junit mockito spy junit-jupiter