[英]How to mock a method in Java for testing
我有一個methodB
A,它有一個方法 A 在methodA
B 中調用方法 B。
在class B方法B在methodC
methodB
調用方法C。
Class C 實現methodC
。
我正在嘗試使用 junit、mockito 測試methodA
A 中的方法 A。
@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);
}
我收到 null pointer exception for class C methodC
的錯誤。 我也需要嘲笑它嗎? 有沒有一種方法可以模擬methodB
以便測試確實回復methodB
中的實現? 由於我的目標是測試methodA
,我可以使用 mocking 其他方法。
你不是 mocking ClassB
,你正在使用真正的實現:
@Spy
@InjectMocks
ClassB classB;
如果你想模擬它,你需要刪除這兩個注釋並使用@Mock
代替:
@Mock
ClassB classB;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.