Mockito间谍抛出存根异常

时间:2019-03-06 13:52:57

标签: spring spring-boot kotlin mockito

我正试图间谍restTemplate,我想对'exchange'方法存根

以下是一些代码:

间谍班

@Bean
  fun mockedRestTemplate(): RestTemplate = Mockito.spy(RestTemplate::class.java)

另一堂课

   val headers = HttpHeaders()
   headers.setBasicAuth(UUID.randomUUID().toString(), UUID.randomUUID().toString())

   val responseBody = "some error message"

   val ex = HttpClientErrorException.create(
        HttpStatus.NOT_FOUND,
        "random",
        headers,
        responseBody.toByteArray(),
        Charset.defaultCharset()
    )

   val httpEntity = HttpEntity(Any(), headers)

   Mockito.doThrow(ex).`when`(restTemplate).exchange(
            any() ?: config.randomEndpoint,
            any(HttpMethod::class.java) ?: HttpMethod.POST,
            any() ?: httpEntity,
            any() ?: Foo::class.java
   )

我在这里可能做错了什么?我收到此错误消息:

    org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at test.suites.controller.FooTest.canGetFailedErrorFieldsIfApiRejectsRequest(FooTest.kt:468)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

当我在嘲笑/监视其他类时,它工作正常

2 个答案:

答案 0 :(得分:1)

匹配程序(例如sync)只能在any()调用中使用。你有:

verify()

在构造对象而不验证方法调用时,不能在此上下文中使用val httpEntity = HttpEntity(Any(), headers) 。您需要在此处传递实际值。

旁注:any()用于包装真实实例。如果您只是在模拟接口(spy()),则应该改用RestTemplate

答案 1 :(得分:0)

我找到了问题,但我仍然没有找到原因。问题出在config.randomEndpoint中。当我将值更改为字符串类型而不注入配置类时,错误消失了。