2014-11-02 88 views
0

我使用Play Framework 2.0 - 给定我有一个PaymentService来访问数据库。集成测试服务层播放框架

今天我首先发射测试服务器测试:

// set up and start the fake web application 
FakeApplication fakeApp = fakeApplication(inMemoryDatabase()); 
start(fakeApp); 
// get the JPAPlugin through the fake app, and start it 
Option<JPAPlugin> jpaPlugin = fakeApp.getWrappedApplication().plugin(JPAPlugin.class); 
jpaPlugin.get().onStart(); 
// then through the JPA plugin, get access to the entity manager 
final EntityManager manager = jpaPlugin.get().em("default"); 
// and bind it in the thread local 
JPA.bindForCurrentThread(manager); 
JPA.em().getTransaction().begin(); 

做到这一点我可以开始访问数据库,插入前的状态,执行该服务的方法,并断言之后(DB)发布状态

但是,当我测试服务层仅用于访问实体管理器时,启动整个Web服务器(即使它是假服务器)并不合适。

有没有更智能的方法来集成测试服务层? 来自Spring世界,我认为应该可以手动创建实体管理器,而不是让Play服务器为我们做。

任何帮助/提示/方向表示赞赏。

回答

0

我建议使用TestServer类以及Helpers类。你可以用它从junit测试中运行内存中的实例,然后对这个实例运行假请求。实例和你的插件将使用你的application.conf初始化。

最低配置:

app = fakeApplication(inMemoryDatabase()); 
server = Helpers.testServer(9009, app); 
webDriver = play.api.test.WebDriverFactory.apply(HTMLUNIT); 
Helpers.start(server); 
browser = Helpers.testBrowser(webDriver); 

实际测试:

Result result = Helpers.route(Helpers.fakeRequest(GET, "/data...")); 
assertNotNull(result); 

还有要记得清理:

browser.quit(); 
Helpers.stop(server); 
+0

感谢,就像魅力! – 2014-11-04 14:36:18

+0

我很高兴能帮上忙。 – 2014-11-04 15:15:17