2012-11-28 45 views
1

當運行這樣玩2框架測試模擬會話和POST?

@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

這些是硒測試與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); 
     } 
    }); 
    } 
} 

還檢查了這樣的回答:How to manipulate Session, Request and Response for test in play2.0