Play 2.5.x junit test error handling with fakeRequest

本秂侑毒 提交于 2019-12-24 10:58:54

问题


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.



来源:https://stackoverflow.com/questions/40189844/play-2-5-x-junit-test-error-handling-with-fakerequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!