Reputation: 369
I am new to Scala and am writing some tests for Play app in Scala. The Play app has already been written in Java.
I have a RefreshService that has one public method process
public RefreshResponse process(RefreshRequest request) throws Exception {
return this.oauthService.token(request.oauthUrl, request.clientId, request.clientSecret, request.refreshToken)
.thenCompose(oauthToken -> this.processHelper(request.withOAuthToken(oauthToken)))
.get();
}
Where actions are defined in another package as a POJOs
I have written my tests based on the Scala guides
When trying to mock this service I used the following code
var mockRefreshService = mock[RefreshService]
when(mockRefreshService.process(_: RefreshRequest))
thenReturn (new RefreshResponse)
I get the following compiler error from Scala and cannot figure out how the types can be ambigous
[error] /home/joey/Projects/sntdb/test/controllers/ApiControllerSpec.scala:31: overloaded method value thenReturn with alternatives:
[error] (x$1: actions.RefreshRequest => actions.RefreshResponse,x$2: actions.RefreshRequest => actions.RefreshResponse*)org.mockito.stubbing.OngoingStubbing[actions.RefreshRequest => actions.RefreshResponse]
[error] (x$1: actions.RefreshRequest => actions.RefreshResponse)org.mockito.stubbing.OngoingStubbing[actions.RefreshRequest => actions.RefreshResponse]
[error] cannot be applied to (actions.RefreshResponse)
[error] when(mockRefreshService.process(_: RefreshRequest)) thenReturn (new RefreshResponse)
If anymore information is needed please let me know. Otherwise if anyone has any ideas it would be appreciated.
Upvotes: 2
Views: 7462
Reputation: 304
I had the same issue and the only thing that helped me is to extract parameter into variable. For some reason it worked:
var mockRefreshService = mock[RefreshService]
val response = new RefreshResponse
when(mockRefreshService.process(_: RefreshRequest))
thenReturn(response)
Upvotes: 0
Reputation: 369
I solved this, but would love some insight into why this worked.
I replaced _: RefreshRequest with any[RefreshRequest] I understand this I think.
But the imports have me tripped up.
I imported
import org.mockito.ArgumentMatchers.any
and thats when everything worked
when I imported
import org.mockito.Matchers.any
I got a error
value any is not a member of org.mockito.Matchers.any
Looking at the docs for Matchers it is a subclass of Argument Matchers so how did it not have any?
Upvotes: 1
Reputation: 1497
If you use mockito-scala
you can mix-in the trait org.mockito.ArgumentMatchersSugar
and it will provide all the appropriate ones, furthermore, for any
you don't need to specify the type anymore as the compiler will figure it out
Check https://github.com/mockito/mockito-scala for more info
Disclaimer: I develop that library (but is part of the mockito suite anyway)
Upvotes: 2