2

I have a real strange behavior going on. It seems that Mockito is calling the real method on a mocked class, resulting in a NullPointerException. I am mocking the Context object present in the Javalin http framework for Java.

This is the minimal code that results in an exception.

import io.javalin.http.Context;
import org.mockito.Mockito;

public class Main {
    public static void main(String[] args) {
        Context ctx = Mockito.mock(Context.class);
        Mockito.when(ctx.queryParam("hello")).thenReturn("test");
    }
}

I get

    at io.javalin.http.Context.queryString(Context.kt:285)
    at io.javalin.http.Context.queryParamMap(Context.kt:282)
    at io.javalin.http.Context.queryParams(Context.kt:279)
    at io.javalin.http.Context.queryParam(Context.kt:266)
    at io.javalin.http.Context.queryParam$default(Context.kt:266)
    at io.javalin.http.Context.queryParam(Context.kt)
    at Main.main(Main.java:9)

But its not supposed to call the real code! What is going on?

feggak
  • 31
  • 4
  • If that's your minimal code that _actually_ works, then it is quite clear why this doesn't work. Mockito has no static mocking and other code is still able to call `new Context(...)` to get a real Javalin object. – Tom Oct 18 '19 at 08:12
  • Not sure what you mean Tom, that code does not work, it's the minimal example that actually returns an exception. The reason for this turned out to be what I describe below. – feggak Oct 19 '19 at 10:39

1 Answers1

1

You're not really adding tests correctly. Instead of creating them in the main method, create a test class and then annotate your tests with the @Test annotation (will need JUnit for this). You should then be able to run the tests using your IDE.

MattYews
  • 36
  • 1