问题
I have two unit tests that fails because of "[RuntimeException: Missing CSRF Token]":
running(testServer(3333, provideFakeApplication()), () -> {
assertThat(WS.url("http://localhost:3333").get().get(3000).getStatus()
).isEqualTo(OK);
and
running(testServer(3333, provideFakeApplication()), HTMLUNIT, browser -> {
browser.goTo("http://localhost:3333");
assert....
How can I add a session with a CSRF token to the WS.url and the browser.goTo?
The tests are trying to reach a page that has a form.
回答1:
A global solution would be to use a fake application that has the CSRF filter enabled. To do that you need to modify (i.e. create a class that inherits from WithApplication
and override) your provideFakeApplication()
such as it creates the fake application passing in the global settings:
public abstract class TestWrapper extends WithApplication {
public class GlobalTestSettings extends play.GlobalSettings {
@Override
public <T extends EssentialFilter> Class<T>[] filters() {
return new Class[] { CSRFFilter.class };
}
}
@Override
protected FakeApplication provideFakeApplication() {
stop(fakeApplication()); // Stop the existing fake app and start over
Map<String, String> addConfig = new HashMap<>();
return fakeApplication(addConfig, new GlobalTestSettings());
}
}
来源:https://stackoverflow.com/questions/43587025/play-framework-csrf-token-generation-in-unit-test