在单元测试中播放Framework CSRF令牌生成 [英] Play Framework csrf token generation in unit test

查看:113
本文介绍了在单元测试中播放Framework CSRF令牌生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个单元测试由于"[RuntimeException:缺少CSRF令牌]"而失败:

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);

running(testServer(3333, provideFakeApplication()), HTMLUNIT, browser -> {
    browser.goTo("http://localhost:3333");
    assert....

如何将带有CSRF令牌的会话添加到WS.url和browser.goTo?

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.

推荐答案

全局解决方案是使用启用了CSRF筛选器的伪造应用程序.为此,您需要修改(即创建一个从WithApplication继承并覆盖的类)您的provideFakeApplication(),例如它创建传入全局设置的伪造应用程序:

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());
    }
}

这篇关于在单元测试中播放Framework CSRF令牌生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆