Reputation: 45
I'm working on a scala project and in my unit test I have to stub a method that takes as argument a Date(that is instanciated when calling the method), and I can't get to stub it porperly
However, I was able to find a turnaround using this post How to mock new Date() in java using Mockito But I wonder if there is a better way to do this because I find that solution not very satisfying ...
here is the code I try to stub :
def foo(): Future[JsonObject] ={
[...]
for {
a <- b.bar(arg,atDate = Some(Date.from(Instant.now())))
} yield a
}
I tried to stub it like that
val b = mock[B]
when(b.bar(arg, _:Option[Date])).thenReturn(Future.successful(List()))
this doesn't parse,so I have to change it to :
val b = mock[B]
when(b.bar(arg, _:Option[Date])).thenReturn({ d:Date => Future.successful(List())})
and when I run it I have the following error :
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
Maybe I'm missing something in the error message but I don't find it helpful. Is there any way to tell the stub to take whatever value for the date? Also why does it require to put a function in thenReturn part, although the return type of the function is Future[List[A]]?
thanks in advance
Upvotes: 1
Views: 594
Reputation: 1497
You have to use the any
matcher, so your code looks like (here I'm assuming arg
is a variable defined somewhere else in your test code)
when(b.bar(ArgumentMatchers.eq(arg), ArgumentMatchers.any())).thenReturn(Future.successful(List()))
Now that's a bit verbose, so if you upgrade to mockito-scala and use the idiomatic syntax it would look like
b.bar(arg, *) returns Future.successful(List())
if you have/use cats, you can even do
b.bar(arg, *) returnsF List()
for more info check the docs here
Upvotes: 1