Reverse routing in junit testing does not return the full url of the controller that is declared in a splited route file

Viewed 36

I have the following setup:

Java Play framework version 2.8.13

sbt.version=1.3.13

routes file:

-> /v1/bar Foo.Routes

Foo.routes file:

GET /foo    controllers.FooController.index(request: Request)

FooController file:

package controllers;

import play.mvc.Controller;
import play.mvc.Http.Request;
import play.mvc.Result;

public class FooController extends Controller {

  public Result index(Request request) {
    return ok("hello world");
  }
}

FooTests file:

package test;

import static org.junit.Assert.assertEquals;

import controllers.routes;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FooTests {

  private static final Logger LOG = LoggerFactory.getLogger(FooTests.class);

  @Test
  public void test001() {
    var fooUrl = routes.FooController.index().url();
    LOG.debug("fooUrl: {}", fooUrl);
    assertEquals("/v1/bar/foo", fooUrl); // /foo fail
  }

  @Test
  public void test002() {
    var fooUrl = new ReverseFooController(() -> "/v1/bar").index().url();
    LOG.debug("fooUrl: {}", fooUrl);
    assertEquals("/v1/bar/foo", fooUrl); // ok
  }
}

How can I get in my unit tests the full url (/v1/bar/foo) of the controller method ?

Reversing the controller (test001()) does not work, it returns only the path from it's containing Foo.routes file (/foo).

The only solution I found is instantiating the reverted controller (test002()), but I don't like hard coding the prefix like this. It defeats the whole purpose of reverting routes to get the url.

Can I dynamically retrieve the full url (/v1/bar/foo) of the controller inside my unit tests having this split routes strategy ?

I put the source in a repo here

0 Answers
Related