【问题标题】:Integration test Service layer Play Framework集成测试服务层 Play Framework
【发布时间】:2014-11-04 23:15:34
【问题描述】:

我正在使用 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 服务器为我们做这件事。

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

【问题讨论】:

    标签: playframework-2.0


    【解决方案1】:

    我建议使用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);
    

    【讨论】:

    • 很高兴能帮上忙。
    猜你喜欢
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多