Skip to content

jooby-test: NullPointerException when using MockRouter::tryError with custom error handler #3787

@zoltan-kollar

Description

@zoltan-kollar

Please see the code snippet below illustrating an issue I encountered when testing an ErrorHandler with MockRouter's tryError method.

The snippet does the following:

  1. Configures a Jooby application with a custom ErrorHandler that catches CustomException.
  2. Asserts the custom ErrorHandler by creating a MockRouter and invoking its tryError method.

Expectation

  • The assertion in ApplicationTest::test runs and passes.

Observed behaviour

Example code snippet

package joobysandbox;

import io.jooby.Jooby;
import io.jooby.StatusCode;
import io.jooby.problem.HttpProblem;
import io.jooby.test.MockContext;
import io.jooby.test.MockRouter;
import org.junit.jupiter.api.Test;

import static joobysandbox.Application.CustomException;
import static org.junit.jupiter.api.Assertions.assertEquals;

class ApplicationTest {

    private final MockRouter router = new MockRouter(new Application()).setFullExecution(true);

    @Test
    void test() {
        var ctx = new MockContext();
        router.tryError(new CustomException(), ctx); // throws java.lang.NullPointerException
        assertEquals(StatusCode.BAD_REQUEST, ctx.getResponseCode());
    }
}

class Application extends Jooby {
    {
        get("/throw", _ -> {
            throw new CustomException();
        });

        error(CustomException.class, (ctx, _, statusCode) -> {
            var problem = HttpProblem.badRequest("A Client Error — Obviously");
            ctx.getRouter().getErrorHandler().apply(ctx, problem, statusCode);
        });
    }

    public static void main(String[] args) {
        runApp(args, Application::new);
    }

    static class CustomException extends RuntimeException {}
}

Expectation details

java.lang.NullPointerException: Cannot invoke "io.jooby.Router.getErrorHandler()" because the return value of "io.jooby.Context.getRouter()" is null

	at joobysandbox.Application.lambda$new$0(Application.java:34)
	at io.jooby.Router.lambda$error$0(Router.java:747)
	at io.jooby.test.MockRouter.tryError(MockRouter.java:476)
	at joobysandbox.ApplicationTest.test(Application.java:20)

Environment

jooby and jooby-test v4.0.7
junit-jupiter v6.0.0
JDK 24

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions