Play 1.x框架学习之一:功能测试 (functional test in play framework)

Play框架中已经集成了junit框架,你们能够很是方便的进行功能测试,这里我展示一个测试新增的例子,其余的你们能够照这个例子深刻。 首先须要在app/modules包中定义一个Beat类,app/controllers中定义一个控制器Beats,同时须要定义个被测试的方法,并在conf/routes配置该方法的url地址,分别以下: app/modules/Beat.java:java

package models;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import play.db.jpa.GenericModel;
@Entity
@Table(name = "beat")
public class Beat extends GenericModel {
	@Id
	public Long id;
	public String words;
	public Long count;
	public Long attime;
}

app/controllers/Beats.java:数据库

package controllers;

import play.db.jpa.JPABase;
import play.mvc.Controller;
import models.Beat;

public class Beats extends Controller{
	public static void add(Beat beat){
		boolean result = beat.create();
		renderText(result);
	}
}

conf/routes片断:mvc

POST        /beat                Beats.add

Play中用yaml格式文件做为测试的数据存储。也提供了相应的解析方法。这里咱们将测试的数据分红两部分,一部分用做模拟数据库数据,程序启动的时候,会将这部分数据加载到内存数据库中。另外一部做为请求的数据,每次请求的时候会用到。对应的会有两个yaml文件,test/yml/db/beat.yml 和 test/yml/request/beats.yml。 test/yml/db/beat.yml:app

Beat(b1):
  id: 1001
  words: this is a happay word
  count: 0
  
Beat(b2):
  id: 1002
  words: preo jobs
  count: 2

test/yml/request/beats.yml:框架

add_normal:
  beat.id: '1003'
  beat.words: third feel is unok
  beat.count: '0'

这样咱们就能够进行功能测试,功能测试类必须继承FunctionalTest,继承以后就可使用play给咱们预置的各类assert方法,还有junit的注解标签。如:test/function/BeatsTest.java。内容:测试

package function;

import java.util.Map;
import models.Beat;

import org.junit.Before;
import org.junit.Test;
import play.db.jpa.JPA;
import play.mvc.Http.Response;
import play.test.Fixtures;
import play.test.FunctionalTest;

public class BeatsTest extends FunctionalTest{
	Map allRequstMap =null;
	
	@Before
	public void init(){
		allRequstMap = (Map)Fixtures.loadYamlAsMap("yml/request/beats.yml");
    	if(!JPA.em().getTransaction().isActive()){
    		JPA.em().getTransaction().begin();
    	}
    	
    	Fixtures.delete(Beat.class);
    	Fixtures.loadModels("yml/db/beat.yml");
    	JPA.em().getTransaction().commit();
	}
	
	@Test
	public void testAdd(){
		int beforeRequestSize = Beat.findAll().size();
		
		Map map = allRequstMap.get("add_normal");
		Response response = POST("/beat", map);
		assertIsOk(response);
		
		int afterRequestSize = Beat.findAll().size();
		assertEquals(beforeRequestSize, afterRequestSize - 1);
		
		Beat beat = Beat.findById(Long.parseLong(map.get("beat.id")));
		assertNotNull(beat);
		
		String result = response.out.toString();
		assertFalse("null".equals(result));
		assertEquals("true", result);
	} 
}

每次执行@Test方法时,都要先执行init,在init方法中,Fixtures加载解析yaml文件。分别将两个yml文件放入map与内存数据库中。 在testAdd中,使用了FunctionalTest预置的POST发起请求,固然还有其余如PUT/GET/DELETE方法,FunctionalTest也预置的许多assert方法,方便你们的使用,你们能够本身查看API或者源码。this

相关文章
相关标签/搜索