Issue
Consider the below code,
JAXBElement<Response> jaxb=(JAXBElement<Response>) service.getResponse("abc",2000); //getResponse return an Object.
Response resp=jaxb.getValue(); // Null Pointer Exception
Now in JUnit I am mocking the "service.getResponse(...)"
@Mock
Service service;
when(service.getResponse(anyString(),anyInt()).thenReturn(new Response("value"));
Why am I getting NullPointerException here? Is this not the way to mock the given line?
Solution
You have to mock the response aswell.
JAXBElement<Response> jaxb=(JAXBElement<Response>) service.getResponse("abc",2000); //getResponse return an Object.
Response resp=jaxb.getValue(); // Null Pointer Exception
Junit here,
@Mock
Service service;
JAXBElement response = mock(JAXBElement.class);
when(service.getResponse(anyString(),anyInt()).thenReturn(response);
when(response.getValue()).thenReturn(something);
Answered By - Pirate
Answer Checked By - Katrina (JavaFixing Volunteer)