1

当运行这样的网络测试时

@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?谢谢 :-)

4

1 回答 1

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

另请查看此答案:如何在 play2.0 中操作会话、请求和响应以进行测试

于 2012-11-29T07:03:53.017 回答