我们正在使用Mockito来模拟对象。如何模拟在服务代码中创建的对象?以下是服务代码和测试代码。有帮助吗?我现在也不想使用Powermock。
public class EventPublisher {
public void publishEvent(final String eventJson) {
try {
ObjectMapper objectMapper = getObjectMapper(true);
Test testJson = objectMapper.writeValueAsString(event);
testJson.getName();
} catch (JsonProcessingException e) {
return;
}
//publish(); some external call
}
private ObjectMapper getObjectMapper(boolean enableRootElement) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, enableRootElement);
return objectMapper;
}
}
测试代码:
public void testPublishEvent() throws Exception {
ObjectMapper objectMapper = mock(ObjectMapper.class);
when(objectMapper.writeValueAsString(json))
.thenThrow(mock(JsonProcessingException.class)); //this is not getting invoked
}
答案 0 :(得分:0)
感谢您的建议。虽然代码重构是个好主意,但由于该方法在多个地方使用。而不是增加解决方案下面的测试范围来解决当前问题。
public class EventPubliserTest {
@Mock
private ObjectMapper objectMapper;
private class MockEventPublisher extends EventPublisher {
@Override
protected ObjectMapper getObjectMapper(boolean flag) {
return objectMapper;
}
}
@Test
public void testPublishEvent() throws Exception {
EventPublisher eventPublisher = new MockEventPublisher();
when(objectMapper.writeValueAsString(json)).thenThrow(mock(JsonProcessingException.class));
//create or mock some json string
eventPublisher.publishEvent(json);
}
}