`

Play framework 2.0 -测试

 
阅读更多

#测试应用程序

 

测试资源文件必须放在应用的test目录下。你可以通过play控制台使用test和test-only来执行测试任务。

 

1.使用JUnit

 

Play2.0默认使用JUnit进行测试。

package test;

	import org.junit.*;

	import play.mvc.*;
	import play.test.*;
	import play.libs.F.*;

	import static play.test.Helpers.*;
	import static org.fest.assertions.Assertions.*;

	public class SimpleTest {

	    @Test 
	    public void simpleCheck() {
		int a = 1 + 1;
		assertThat(a).isEqualTo(2);
	    }
	    ...
 

 

2.在伪应用程序中运行

 

如果你需要测试的代码依赖一个运行中的程序,你可以在fly上轻松的创建一个FakeApplication。

@Test
	public void findById() {
	    running(fakeApplication(), new Runnable() {
	       public void run() {
		   Computer macintosh = Computer.find.byId(21l);
		   assertThat(macintosh.name).isEqualTo("Macintosh");
		   assertThat(formatted(macintosh.introduced)).isEqualTo("1984-01-24");
	       }
	    });
	}

 

你也快传递(或重写)另外的应用程序配置,或者mock任何插件。例如使用默认的内存数据库创建一个FakeApplication。

fakeApplication(inMemoryDatabase())
 

 

#编写功能测试

 

1.测试模板

 

因为模板是个标准的Scala函数,你可以在test中执行它并检查结果。

@Test
	public void renderTemplate() {
	    Content html = views.html.index.render("Coco");
	    assertThat(contentType(html)).isEqualTo("text/html");
	    assertThat(contentAsString(html)).contains("Coco");
	}
 

 

2.测试你的Controllers

 

通过检索路由,你可以得到一个action的引用,如controllers.routes.ref.Application.index。然后你可以调用它:

@Test
	public void callIndex() {
	    Result result = callAction(controllers.routes.ref.Application.index("Kiki"));   
	    assertThat(status(result)).isEqualTo(OK);
	    assertThat(contentType(result)).isEqualTo("text/html");
	    assertThat(charset(result)).isEqualTo("utf-8");
	    assertThat(contentAsString(result)).contains("Hello Kiki");
	}
 

 

3.测试路由

 

不同于自己调用action,你可以让路由这么做:

@Test
	public void badRoute() {
	    Result result = routeAndCall(fakeRequest(GET, "/xx/Kiki"));
	    assertThat(result).isNull();
	}
 

 

4.启动真的Http服务器

 

有时候你想测试真的Http栈模型。那么你可以启动一个测试服务器:

@Test
	public void testInServer() {
	  running(testServer(3333), new Callback0() {
	      public void invoke() {
		 assertThat(
		   WS.url("http://localhost:3333").get().get().status
		 ).isEqualTo(OK);
	      }
	  });
	}
 

 

4.在web浏览器中测试

 

如果你想在web浏览器中测试你的应用,你可以使用selenum WebDriver。Play会为你启动WebDriver,并且

用FluentLenium提供的简便API包装它。

@Test
	public void runInBrowser() {
	    running(testServer(3333), HTMLUNIT, 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");
		}
	    });
	}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics