Spring boot 如何使用JUnit MapperToJsonString类

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

请帮助我解决关于如何单元测试我的类的问题

这是我无法用JUnit完全覆盖的类

@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))这是为null
    myModelClass=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());