Reputation: 541
I am using Play Framework 2.3 and have made a database evolution that is somewhat involved and requires updating new fields with values computed from old fields (that are removed in the evolution). It would be nice to test that the evolution works as expected: that is, check that the new fields have been populated with the right values. However, I have not been able to find a best practice for testing a database evolution. In fact, I am not even sure how to apply an evolution during a test.
Any suggestions?
Upvotes: 4
Views: 987
Reputation: 401
So, with Play you can easily write integration tests using an instance of FakeApplication. See https://www.playframework.com/documentation/2.2.x/JavaTest for the basics.
Also you can setup a custom Evolution instance, to use in your test.
Here is just a simple example in 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);
}
}
After running the evolutions test you could write test cases using simple ebean queries to check your populated values.
Upvotes: 1