简体   繁体   中英

How to mock a method in Java for testing

I have a class A which has a methodA calling a methodB in class B.

In class B methodB is calling methodC in class C.

Class C implements methodC .

I am trying to test methodA in class A using junit, mockito.

@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);
 
    }

I am getting an error of null pointer exception for class C methodC . Do I need to mock that as well? Is there a way I can mock methodB so that the test does reply on the implementation in methodB ? As my aim is to test methodA , I am fine mocking other methods.

You are not mocking ClassB , you are using the real implementation:

@Spy
@InjectMocks
ClassB classB;

If you want to mock it, you need to remove those two annotations and have @Mock instead:

@Mock
ClassB classB;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM