集成测试服务层Play框架

时间:2014-11-02 23:30:24

标签: playframework-2.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();

完成此操作后,我可以开始访问数据库,插入pre状态,执行服务上的方法,以及断言(DB)post state

但是当我测试服务层只是为了获得对实体管理器的访问权时,它不适合启动整个Web服务器(即使它是一个虚假的服务器)。

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

感谢任何帮助/提示/指示。

1 个答案:

答案 0 :(得分: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);
相关问题