我正在获得一个空的JSON {}
(通过actions.andReturn().getResponse().getContentAsString()
验证)作为响应,当我通过mockMvc.perform(post...))
测试,该方法实际上返回了响应(我在我调试并逐步浏览代码。这是一个有效的,填充的响应对象,但是当Mockito中的某些代码制作模式时,突然变为null-为什么这样做?)。
测试类:
@RunWith(MockitoJUnitRunner.class)
public class Test
{
//Also tried @Mock
@InjectMocks
private MyService myService;
@Mock
private MyDAO myDAO;
//@Autowired
@InjectMocks
private MyController myController;
@Before
public void setup() {
//Build the controller mock handler
mockMvc = MockMvcBuilders
.standaloneSetup(myController)
.setControllerAdvice(new ExceptionHandler())
.build();
}
@org.junit.Test
public void testMyEndpoint() throws Exception
{
//Make a request object
MyRequest request = readJson("request.json", MyRequest.class );
List<MyObject> objects = readJson("data.json", MyObject.class );
Mockito.when(
myDAO.getData( request )
).thenReturn(objects);
Mockito.when(
myService.callDAO(request)
)
.thenReturn(objects)
//Call the aum endpoint
ResultActions actions = mockMvc.perform(
post( "/v1/endpoint" )
.contentType(MediaType.APPLICATION_JSON)
.content( new ObjectMapper().writeValueAsString( request ) )
);
//Why is this empty?
System.out.println( actions.andReturn().getResponse().getContentAsString() );
}
}
Mockito使用不了解 @JsonView
的对象模具。要解决这个问题,您需要设置一个可以做的消息转换器。
@RunWith(MockitoJUnitRunner.class)
public class Test
{
//Also tried @Mock
@InjectMocks
private MyService myService;
@Mock
private MyDAO myDAO;
//@Autowired
@InjectMocks
private MyController myController;
/**
* This is required for JsonViews.
* @return
*/
public static MappingJackson2HttpMessageConverter createJacksonConverter() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper);
return converter;
}
@Before
public void setup() {
//Build the controller mock handler
mockMvc = MockMvcBuilders
.standaloneSetup(myController)
.setControllerAdvice(new ExceptionHandler())
.setMessageConverters(createJacksonConverter())
.build();
}
@org.junit.Test
public void testMyEndpoint() throws Exception
{
//Make a request object
MyRequest request = readJson("request.json", MyRequest.class );
List<MyObject> objects = readJson("data.json", MyObject.class );
Mockito.when(
myDAO.getData( request )
).thenReturn(objects);
Mockito.when(
myService.callDAO(request)
)
.thenReturn(objects)
//Call the aum endpoint
ResultActions actions = mockMvc.perform(
post( "/v1/endpoint" )
.contentType(MediaType.APPLICATION_JSON)
.content( new ObjectMapper().writeValueAsString( request ) )
);
//Why is this empty?
System.out.println( actions.andReturn().getResponse().getContentAsString() );
}
}