用于在Java Play中测试的HTTP上下文! 2.0.2 [英] HTTP Context for testing in Java Play! 2.0.2

查看:104
本文介绍了用于在Java Play中测试的HTTP上下文! 2.0.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试为视图编写测试,但其中一些需要会话变量才能正确呈现。这是标准测试的样子:

We're trying to write tests for our views, but some of them require session variables to properly render. This is what a standard test looks like:

@Test
public void indexTest() {
    running(fakeApplication(), new Runnable() {
        public void run() {
            Content html = views.html.index.render(loginForm);
            assertThat(contentType(html)).isEqualTo("text/html");
            assertThat(contentAsString(html)).contains("log in");
        }
    });
}

loginForm是我们在测试类中声明的模拟形式。

loginForm is a mock form we have declared in the test class.

但是,当我们尝试运行此测试时,我们会收到以下错误:

However, when we try to run this test we get the following error:

'没有可用的HTTP上下文这里'

'There is no HTTP Context available from here'

我们尝试使用testServer并试图从请求到该服务器获取http上下文,但无济于事。

We tried using a testServer and trying to get the http context from requests to that server, but to no avail.

谢谢: - )

编辑 @nico_ekito

Edit @nico_ekito

这是我的loginForm周围的代码:

This is the code surrounding my loginForm:

Form<Login> loginForm = Controller.form(Login.class);

但是,我认为问题在于被调用的控制器,因为视图不使用任何会话属性。然而,authenticate()方法(在控制器中,我相信当表单提交到视图时)会使用会话。

However, I believe the problem lies within the controller being invoked, because the view doesn't use any session properties. The authenticate() method (in the controller, which is being rendered I believe when the form is submitted to the view) however, uses sessions.

推荐答案

如果您发布了整个视图会有所帮助,因为您可能正在使用auth插件/ i18n插件或类似的东西,而这些插件又使用会话属性。在运行测试之前,您还可以尝试使用Mocktio或类似方法模拟上下文。

Would be helpful if you posted the entire view, because you might be using an auth plugin/i18n plugin or something like that which in turn uses session properties. You could also try mocking out the context with Mocktio or similar before running the test.

Context.current.set(
        new Context(mock(Request.class), 
                    new HashMap<String, String>(),  
                    new HashMap<String, String>()));

我建议您再次检查会话属性。

I would recommend going over your views one more time checking for session properties though.

这篇关于用于在Java Play中测试的HTTP上下文! 2.0.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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