Using any<String>() with a spy throws IllegalArgumentException
See original GitHub issueany<String>()
returns null which works with mocks but fails with spies. A simple test to reproduce.
@Test
fun passAnyStringToSpy() {
val my = spy(MyClass())
whenever(my.foo(any())).thenReturn("mocked") // this throws java.lang.IllegalArgumentException: Parameter specified as non-null is null
expect(my.foo("hello")).toBe("mocked")
}
private interface MyInterface {
fun foo(value: String): String
}
private open class MyClass : MyInterface {
override fun foo(value: String) = value
}
It seems that making any<String>()
return ""
solves the problem, but one of the current tests fails:
stubbingTwiceWithCheckArgumentMatchers_throwsException
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:6
Top Results From Across the Web
Using any<String>() with a spy throws IllegalArgumentException
any<String >() returns null which works with mocks but fails with spies. A simple test to reproduce. @Test fun passAnyStringToSpy() { val my...
Read more >Powermockito : java.lang.IllegalArgumentException: argument ...
when(spyObject, "lockUser", anyObject(), anyString(), anyString(), anyString());. All lockUser methods are priavate. I am working with Mockito ...
Read more >Mocking Exception Throwing using Mockito | Baeldung
Learn to configure a method call to throw an exception in Mockito. ... First, if our method return type is not void, we...
Read more >Java – mockito better expected exception test using spy
Mockito.spy(a); // valid but doesnt work // doThrow(new IllegalArgumentException()).when(spyA).doSomethingThatThrows(); // invalid but in the spirit of what ...
Read more >A Unit Testing Practitioner's Guide to Everyday Mockito - Toptal
In this article, we'll cover multiple mock interfaces, listening invocations, matchers, and argument captors, and see firsthand how Mockito makes your tests ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Due to
any()
returningnull
and the methodfoo
being executed with it, theIllegalArgumentException
is thrown.To prevent
null
from being passed to the actual code, you can use the alternative syntax as such:Since actually fixing this requires
any()
to not returnnull
which brings a lot of other problems, I propose to close this issue as resolved.It would be nice to have this in the wiki. I spent a few hours trying to figure out why the mock syntax didn’t work for spies 😞 I could amend the wiki, and submit a PR if that helps, @nhaarman ?