java - 用于类型引用的 Mockito 匹配器

标签 java junit mockito

我正在尝试使用 Mockito 编写 Java 单元测试,但无法让匹配器正常工作。

我想测试以下类(class)

CustomService.java

public class CustomService {

private final ApplicationProperties props;

public CustomService(ApplicationProperties props){
    this.props = props;
}

private final ObjectMapper mapper = new ObjectMapper();
public void method(JsonNode message) throws CustomException {
    try {
        List<String> actions = mapper.readValue(message.get("actions").toString(), mapper.getTypeFactory().constructCollectionType(List.class, String.class));
        System.out.println(actions);
    } catch (IOException ex){
        throw new CustomException(ex);
    }
}
}

我有一个 CustomException 类

CustomException.java

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class CustomException extends Exception {

public CustomException(Throwable cause) {
    super(cause);
    }

}

我想测试是否抛出了 CustomException。我正在使用 Mockito。我已尝试以下操作,但 given 语句似乎没有获取方法中的 (readValue) 代码行

CustomServiceTest.java

public class CustomServiceTest {

private final ApplicationProperties props = mock(ApplicationProperties.class);
private final CustomService customService = new CustomService(props);
private static final ObjectMapper objectMapper = new ObjectMapper();

@Test
public void CustomExceptionIsThrown() throws Exception {
    ObjectMapper mapper = mock(ObjectMapper.class);
    given(mapper.readValue(anyString(), any(TypeReference.class))).willThrow(new IOException("This is a test"));
    String json = "{\"actions\":[\"ac1\",\"ac2\",\"ac3\",\"ac4\"]}";
    JsonNode d = objectMapper.readTree(json);
    assertThrows(CustomException.class, () ->
            customService.method(d));
    }
}

运行测试时出现以下错误

Expected exception.CustomException to be thrown, but nothing was thrown..

如果有帮助,我们将不胜感激。

最佳答案

我也遇到了同样的问题,我发现虽然我像“一样模拟objectMapper” when(objectMapper.readValue(anyString(), any(TypeReference.class))).thenReturn(xxxx);”但是当我调用测试时,readValue(xx,xx)的第一个参数是null 应该是一个 String 对象。因此,您可能需要再次检查 readValue 方法输入参数。希望它会有所帮助。

关于java - 用于类型引用的 Mockito 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960396/

相关文章:

java - 是否可以有条件地模拟不带参数的方法?

java - 缓冲记录器 (Java)

java - PrintWriter 对象不会将文本文档中的所有行打印到输出文件中

java - JobLauncherTestUtils 期望至少有 1 个有资格作为 Autowiring 候选者的 bean

java - 如何使用whenNew方法模拟ArrayList类

java - 重构和测试

java - 使用递归打印大小为 n 的所有二进制数

java.lang.ClassNotFoundException : org. springframework.beans.factory.access.BeanFactoryReference

java - 如何模拟 ENUM 类中的方法?

java - 使用 KOTLIN android studio 进行 JUnit 测试 [基本计算器]