Getting a null pointer exception when invoking a method on a mock
See original GitHub issueI have a class:
open class Foo(private val bar: Bar) {
fun print(): String {
return bar.print()
}
}
When I mock this class in java, I get a null pointer exception.
Foo foo = Mockito.mock(Foo.class);
when(foo.print()).thenReturn("value"); // Null pointer exception saying bar is null.
Foo foo = Mockito.mock(Foo.class);
doReturn("value").when(foo).print(); // Null pointer exception saying bar is null.
Foo foo = Mockito.mock(Foo.class);
doReturn("value").when(foo.print()); // Null pointer exception saying bar is null.
With mockito-kotlin:
foo = mock<Foo>()
whenever(foo.print()).thenReturn("value") // Null pointer exception saying bar is null.
How do you get around this?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:4
- Comments:9
Top Results From Across the Web
Mockito - NullpointerException when stubbing Method
Mockito - NullpointerException when stubbing Method · the object in when() must be a mock created by Mockito. · It sounds like classIwantToTest....
Read more >3 basic mistakes for NullPointerException when Mock
1. Return something for your Mock. · 2. Specify Mockito running class · 3. You need to annotate the mocking object with the...
Read more >How to get Mock to return value to avoid NullPointerException ...
The right solution of the problem is to add return value “CAR” to place when we test the first interaction. It means that...
Read more >Null Pointer Exception In Java - GeeksforGeeks
Invoking a method from a null object. · Accessing or modifying a null object's field. · Taking the length of null, as if...
Read more >Mockito 2.2.29 API - javadoc.io
Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.
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
Ok - figured it out - it is because the method is final.
the method needs to be marked
open
for this to work:In my case I was trying to mock a property which was annotated with
@JvmField
. Removing the annotation, which wasn’t needed in my case, did the trick.