玩2框架测试模拟会话和POST?

时间:2012-11-28 17:35:09

标签: testing post playframework playframework-2.0

运行像这样的网络测试时

@Test
public void runInBrowser() {
    running(testServer(3333),  HtmlUnitDriver.class, new Callback<TestBrowser>() {
        public void invoke(TestBrowser browser) {
           browser.goTo("http://localhost:3333"); 
           assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest");
           browser.$("a").click();
           assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco");
           assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco");
        }
    });
}

如何在使用此类测试时传递会话值以及如何模拟POST?谢谢: - )

1 个答案:

答案 0 :(得分:4)

这些是FluentLenium的Selenium测试。由于您使用浏览器进行测试,因此必须使用带有方法POST的HTML表单来发出POST请求。

browser.goTo("http://localhost:3333" + routes.Login.login().url());//example for reverse route, alternatively use something like "http://localhost:3333/login"
browser.fill("#password").with("secret");
browser.fill("#username").with("aUsername");
browser.submit("#signin");//trigger submit button on the form
//after finished request: http://www.playframework.org/documentation/api/2.0.4/java/play/test/TestBrowser.html
browser.getCookies(); //read only cookies

也许您不想使用浏览器进行测试,而是使用HTTP,您可以使用FakeRequests

import static controllers.routes.ref.Application;
import static org.fest.assertions.Assertions.assertThat;
import static play.mvc.Http.Status.OK;
import static play.mvc.Http.Status.UNAUTHORIZED;
import static play.test.Helpers.*;

import play.libs.WS;
import java.util.HashMap;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import play.mvc.Result;
import play.test.FakeRequest;

public class SoTest {
  @Test
  public void testInServer() {
    running(testServer(3333), new Runnable() {
        public void run() {
            Fixtures.loadAll();//you may have to fill your database you have to program this yourself
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("userName", "aUsername");
            parameters.put("password", "secret");
            FakeRequest fakeRequest = new FakeRequest().withSession("key", "value").withCookies(name, value, maxAge, path, domain, secure, httpOnly).withFormUrlEncodedBody(parameters);
            Result result = callAction(Application.signIn(), fakeRequest);
            int responseCode = status(result);
            assertThat(responseCode).isEqualTo(OK);
        }
    });
  }
}

同时查看此答案:How to manipulate Session, Request and Response for test in play2.0