Home > Back-end >  How to resolve ambiguity when mocking mock<RestTemplate> getForObject?
How to resolve ambiguity when mocking mock<RestTemplate> getForObject?

Time:12-16

Using com.nhaarman.mockitokotlin2 for testing restTemplate.getForObject(url, Int::class.java), url is type of String!

Trying to mock RestTemplate::getForObject:

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

But get an error:

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

And

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

Please help, I'm new in Kotlin

CodePudding user response:

You need to tell Mockito that it should expect a String as a first argumet. Try the following:

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

You can read more about anyString() in the reference documentation.

  • Related