Spring boot 如何使用JUnit MapperToJsonString类
请帮助我解决关于如何单元测试我的类的问题 这是我无法用JUnit完全覆盖的类Spring boot 如何使用JUnit MapperToJsonString类,spring-boot,junit,Spring Boot,Junit,请帮助我解决关于如何单元测试我的类的问题 这是我无法用JUnit完全覆盖的类 @Component public class Utils { @Autowired private ObjectMapper mapper = new ObjectMapper(); @Autowired private LoggingService loggingService; public <E> String mapToJsonString(E obj
@Component
public class Utils {
@Autowired
private ObjectMapper mapper = new ObjectMapper();
@Autowired
private LoggingService loggingService;
public <E> String mapToJsonString(E object) {
try {
if (object == null) {
throw new IOException(ErrorMessage.ERROR_PROCESSING_JSON_NULL);
}
return mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object);
} catch (IOException e) {
loggingService.logError(this.getClass().getName(), "1", ErrorMessage.ERROR_MAPPING_TO_JSONSTRING, e);
return "";
}
}
}
任何帮助都将不胜感激。谢谢。您不应该模拟
Utils
对象或mapToJsonString()
方法,因为这是您要测试的方法,您希望调用真实的方法而不是模拟的方法
这意味着junit中不应出现以下语句
Mockito.when(utils.mapToJsonString(myModelClass)).thenReturn("");
Mockito.when(utils.mapToJsonString(null)).thenThrow(new IOException());
首先,我可以考虑以下JUnit,但是您应该考虑更多的场景来测试和编写JUnit
mapToJsonString()
,并断言/验证它返回的JSON字符串null
传递到mapToJsonString()
并断言/验证空字符串。与在catch
块中使用外部对象loggingService
一样,需要模拟loggingService.logError()
调用另外,不要为
@Test(expected=IOException.class)
编写任何junit,因为它永远不会成功,因为您没有在catch块中重新抛出IOException
。感谢@Smile您的回复。但它给了我nullPointerException。调试测试用例时,utils为null。这是我更新后的代码:将对象传递给mapToJsonString()String output=utils.mapToJsonString(myModelClass)代码>assertEquals(输出,utils.mapToJsonString(myModelClass))代码>这是为nullmyModelClass=newmymodelclass()代码>myModelClass=null代码>String输出=utils.mapToJsonString(atm)代码>Mockito.when(loggingService.logError(this.getClass().getName(),“1”,ErrorMessage.ERROR\u映射到\u JSONSTRING,新异常())。然后返回(“”)代码>assertThat(输出).isNull()代码>最好用代码更新您的问题,因为它比注释更具可读性。另外,使用@MockBean
表明您正在使用SpringRunner来运行测试用例。因此,您可以@Autowire
将utils
变量分配给它utils
对象。
Mockito.when(utils.mapToJsonString(myModelClass)).thenReturn("");
Mockito.when(utils.mapToJsonString(null)).thenThrow(new IOException());