Spring 启动 JUnit5:TypeCast 模拟

Spring Boot JUnit5: TypeCast Mocking

考虑下面的代码,

JAXBElement<Response> jaxb=(JAXBElement<Response>) service.getResponse("abc",2000); //getResponse return an Object.

Response resp=jaxb.getValue(); // Null Pointer Exception

现在在 JUnit 中我正在嘲笑“service.getResponse(...)”

@Mock
Service service;

when(service.getResponse(anyString(),anyInt()).thenReturn(new Response("value"));

为什么我在这里得到 NullPointerException?这不是模拟给定行的方法吗?

您还必须模拟响应。

JAXBElement<Response> jaxb=(JAXBElement<Response>) service.getResponse("abc",2000); //getResponse return an Object.

Response resp=jaxb.getValue(); // Null Pointer Exception

Junit 在这里,

@Mock
Service service;

JAXBElement response = mock(JAXBElement.class);
when(service.getResponse(anyString(),anyInt()).thenReturn(response);
when(response.getValue()).thenReturn(something);