Generating a csrf token for the Play Framework in unit test

I have two unit tests that fail 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 to add a session with a CSRF token in WS.url and browser.goTo?

Tests try to find a page with a form.

0
source share
1 answer

The global solution will be to use a fake application in which the CSRF filter is enabled. To do this, you need to change (i.e. create a class that inherits from WithApplication and override) your provideFakeApplication() , for example, it creates a fake application that runs in 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()); } } 
+1
source

Source: https://habr.com/ru/post/1258791/


All Articles