Getting Null Pointer Exception while mocking a class in scala using MockitoSugar

1.4k Views Asked by At

When I mock a class in scala using MockitoSugar and try to access that mock object, I am getting Null Pointer Exception.

import org.apache.hadoop.hbase.util.Pair;

class JobSpec extends FunSpec with MockitoSugar {

    var pairType: Pair[Optional[String],Optional[String]] = mock[Pair[Optional[String],Optional[String]]]

    describe("update") {
        it("run") {
            pairType.getSecond()
        }
    }
}

pairType.getSecond() is throwing NPException.

I expect pairType with some dummy values.

1

There are 1 best solutions below

0
On

couple of things here

a) it is not recommended to mock stuff you don't own, aka library classes

b) by default any mock returns null if it hasn't been stubbed in mockito-core, if you go for mockito-scala it will give you back a non-null value if the return type is non-final

The NPE sometimes can also happend due to Java-Scala interop issues, which may be your case as you don't seem to be using the result of pairType.getSecond(). The solution for that would be to use mockito-scala ;)