【问题标题】:How to resolve ambiguity when mocking mock<RestTemplate> getForObject?模拟 mock<RestTemplate> getForObject 时如何解决歧义?
【发布时间】:2022-01-18 16:25:44
【问题描述】:

使用com.nhaarman.mockitokotlin2 测试restTemplate.getForObject(url, Int::class.java),url 是String! 的类型

试图模拟RestTemplate::getForObject

val restTemplate = mock<RestTemplate> {
        on { getForObject(any(), any()) } doReturn ResponseEntity.ok(Object())
    }

但是得到一个错误:

Overload resolution ambiguity. All these functions match.
public open fun <T : Any!> getForObject(url: URI!, responseType: Class<TypeVariable(T)!>!): TypeVariable(T)! defined in org.springframework.web.client.RestTemplate
public open fun <T : Any!> getForObject(url: String!, responseType: Class<TypeVariable(T)!>!, vararg uriVariables: Any!): TypeVariable(T)! defined in org.springframework.web.client.RestTemplate

Type mismatch.
Required:
Unit
Found:
ResponseEntity<Object!>!

请帮忙,我是 Kotlin 的新手

【问题讨论】:

  • 您能添加您要测试的代码吗?谢谢!
  • restTemplate.getForObject(url, Int::class.java), url 是字符串类型!

标签: kotlin mockito resttemplate


【解决方案1】:

你需要告诉 Mockito 它应该期待 String 作为第一个参数。请尝试以下操作:

val restTemplate = mock<RestTemplate> {
    on { getForObject(anyString(), eq(Int::class.java)) } doReturn 200
}

您可以在reference documentation 中阅读有关anyString() 的更多信息。

【讨论】:

  • 这里是any() 的问题:Not enough information to infer type variable T
  • 我已经更新了我的答案,请查看;)
  • 谢谢,但ResponseEntity.ok(Object()) 有问题:Type mismatch. Required: Int! Found: ResponseEntity&lt;Int!&gt;! 更改为doReturn Int() 不起作用,原因是:Cannot access '&lt;init&gt;': it is private in 'Int' 错误
  • 我的错。鉴于您希望 Int 成为您的 getForObject()call 的响应,您需要在模拟呼叫时返回 Int。请检查我的更新答案。
猜你喜欢
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 2017-10-03
相关资源
最近更新 更多