【问题标题】:How to test database evolutions in Play Framework 2如何在 Play Framework 2 中测试数据库演化
【发布时间】:2015-11-16 11:15:08
【问题描述】:

我正在使用 Play Framework 2.3 并进行了数据库演进,这在一定程度上涉及并需要使用从旧字段(在演进中删除)计算的值更新新字段。测试进化是否按预期工作会很好:也就是说,检查新字段是否填充了正确的值。但是,我还没有找到测试数据库演变的最佳实践。事实上,我什至不确定如何在测试中应用进化。

有什么建议吗?

【问题讨论】:

    标签: playframework playframework-2.3 ebean playframework-evolutions


    【解决方案1】:

    因此,通过 Play,您可以使用 FakeApplication 的实例轻松编写集成测试。有关基本信息,请参阅 https://www.playframework.com/documentation/2.2.x/JavaTest

    您还可以设置自定义 Evolution 实例,以在您的测试中使用。

    这里只是一个简单的java例子:

    @Before
    public void setUp() throws IOException {
      fakeapp = Helpers.fakeApplication(testconfiguration)
      evolutions = Evolutions.applicationEvolutions(fakeapp.getWrappedApplication().path(), fakeapp.getWrappedApplication().classloader(), "database");
      Iterator<Evolution> iterator = evolutions.iterator();
    
      while (iterator.hasNext()) {
        Evolution current = iterator.next();
        if (latestEvolution == null) {
          latestEvolution = current;
        } else {
          latestEvolution = current.revision() > latestEvolution.revision() ? current : latestEvolution;
        }
      }
    
      latestEvolutionFile = new File(fakeapp.getWrappedApplication().path(), "path/to/evolution/files" + latestEvolution.revision() + ".sql");
      latestEvolutionFileContent = Files.readAllBytes(Paths.get(latestEvolutionFile.getAbsolutePath()));
    }
    
    @Test
    public void testLatestDownEvolution() throws IOException {
      try {
        // arrange
        // modify the latest evolution file, so when executing the evolution plugin a 2nd time the latest evolution file will be applied again
        Evolutions.updateEvolutionScript("database", latestEvolution.revision(), "", "", "", fakeapp.getWrappedApplication());
    
        // act
        app.getWrappedApplication().plugin(EvolutionsPlugin.class).get().onStart();
    
        // when no exception has been thrown, then we are fine
    
      } catch (InconsistentDatabase ex) {
        Assert.fail(ex.subTitle() + " " + ex.rev() + ".sql");
      } finally {
        // just bring the modified script back to his original content, cause we don't want to commit that in our VCS...
        try (FileOutputStream stream = new FileOutputStream(latestEvolutionFile)) {
        stream.write(latestEvolutionFileContent);
      }
    }
    

    运行进化测试后,您可以使用简单的 ebean 查询编写测试用例来检查填充的值。

    【讨论】:

    • 感谢您的回答,这部分解决了我的问题。然而,该解决方案仅解决了上下演进执行是否没有错误的测试。由于带有 inMemoryDatabase 的 fakeApplication 总是从空开始,然后应用我们无法在测试用例之前/之后创建的演变,以检查更新语句等是否正确执行。有没有办法将数据库设置为某个进化版本,填充一个表,然后运行后续的进化?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多