Play 2.5.x junit test error handling with fakeRequ

2019-07-25 11:17发布

问题:

My program uses global error handling. When i using fakeRequest() to test, it throws out exception instead of trigger my error handler. Am I missing some configuration? Or how can I test my global error handler.

Below is my current code:

Controller:

public class MyController {
    public Result MyService() {
        if (true) throw new RuntimeException("exception");
    }
}

ErrorHandler:

@Singleton
public class MyErrorHandler extends DefaultHttpErrorHandler {

  @Inject
  public MyErrorHandler (Configuration configuration, Environment environment, OptionalSourceMapper sourceMapper, Provider<Router> routes) {
    super(configuration, environment, sourceMapper, routes);
  }

  @Override
  public CompletionStage<Result> onServerError(Http.RequestHeader request, Throwable exception) {
    return CompletableFuture.completedFuture(ok(exception.getMessage()));
  }
}

Test:

public class MyTest {
  @Test
  public void testMethod() {
    Result result = route(fakeRequest("GET", "/MyService"));
    assertEquals(OK, result.status());
  }
}

Note: When I run application, the error handling is working as expected.

回答1:

The lack of error handler in the unit test flow is by design. It is meant to be like that.

With a simple router, you can get around this problem.

This link might be of some help for both of these points: https://github.com/playframework/playframework/issues/2484

Not repeating the contents of the link here.