Tanu
Tanu

Reputation: 1634

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.

Upvotes: 0

Views: 988

Answers (1)

&#201;tienne Miret
&#201;tienne Miret

Reputation: 6660

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;

Upvotes: 1

Related Questions