0

Example response handler:

private static void handleGetRequest(RoutingContext ctx) {
    final HttpServerResponse response = ctx.response;
    try {
        A a = B.getSomeA();
        a.handleSomething();
    }
    catch (Exception ex) {System.out.println(ex);}
}

How do we unit test the above handler by mocking objects within the handler?

homerman
  • 3,369
  • 1
  • 16
  • 32

1 Answers1

0

You need to introduce a seam where instances of A are provided to the Handler. Such a seam allows you to introduce mocks/stubs/fakes for testing purposes.

The solution could be something as simple as:

  class MyHandler implements Handler<RoutingContext> {
    private final Supplier<A> aSupplier;

    MyHandler(Supplier<A> aSupplier) { // <-- this is your test seam
      this.aSupplier = aSupplier;
    }

    @Override
    public void handle(RoutingContext ctx) {
      final HttpServerResponse response = ctx.response();
      try {
        A a = aSupplier.get(); // <-- a mocked version can return 'A' in any state
        a.handleSomething();
      }
      catch (Exception ex) {System.out.println(ex);}
    }
  }

Separating the Handler out as its own type gives the added benefit of being able to test it in isolation, but isn't absolutely necessary.

homerman
  • 3,369
  • 1
  • 16
  • 32