play-framework:使用假应用程序进行测试

时间:2013-03-07 21:48:41

标签: playframework-2.0 playframework-2.1

我正在尝试测试这样的功能:

@Test
    public void testAddTask() {
        FakeApplication fakeApplication = fakeApplication(inMemoryDatabase());
        start(fakeApplication);
        Task task=new Task();
        task.title="test Task";
        task.save();
        assertThat(Task.find.where().ilike("title", "task")).isNull();
        stop(fakeApplication);

    }

哪个成功哪个是错的 而

@Test
    public void testAddTask(){
        running(fakeApplication(inMemoryDatabase()), new Runnable() {
            public void run() {
                Task task=new Task();
                task.title="test Task";
                task.save();
                assertThat(Task.find.where().ilike("title", "task")).isNull();
            }
        });
    }

失败,这就是我的期望。

startfakeapplication的行为不应该与`running(fakeApplication()?

相同

1 个答案:

答案 0 :(得分:2)

是的,does the same

/**
 * Executes a block of code in a running application.
 */
public static synchronized void running(FakeApplication fakeApplication, final Runnable block) {
    try {
        start(fakeApplication);
        block.run();
    } finally {
        stop(fakeApplication);
    }
}

运行其他测试后,可能无法清除差异原因。 running()具有try..finally构造,建议将stop(fakeApplication);放入使用@After注释的方法中(并在fakeApplication中初始化@Before)。

我不喜欢running()辅助方法,因为它不允许在run()内抛出异常。