重头戏 2 框架测试模拟会话和开机自检



运行这样的 Web 测试时

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

这些是使用FluentLenium进行的硒测试。由于您使用浏览器进行测试,因此必须使用带有方法 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中操作会话,请求和响应进行测试

最新更新