2014-11-02 82 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