001/* 002 * Licensed under the Apache License, Version 2.0 (the "License"); 003 * you may not use this file except in compliance with the License. 004 * You may obtain a copy of the License at 005 * 006 * http://www.apache.org/licenses/LICENSE-2.0 007 * 008 * Unless required by applicable law or agreed to in writing, software 009 * distributed under the License is distributed on an "AS IS" BASIS, 010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 011 * See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014package de.softwareforge.testing.postgres.junit5; 015 016import static org.junit.jupiter.api.Assertions.assertEquals; 017import static org.junit.jupiter.api.Assertions.assertNotEquals; 018 019import de.softwareforge.testing.postgres.embedded.DatabaseInfo; 020import de.softwareforge.testing.postgres.embedded.FlywayPreparer; 021 022import java.sql.Connection; 023import java.sql.ResultSet; 024import java.sql.SQLException; 025import java.sql.Statement; 026 027import org.junit.jupiter.api.Test; 028import org.junit.jupiter.api.extension.RegisterExtension; 029 030public class JUnit5FlywayTest { 031 032 @RegisterExtension 033 public static EmbeddedPgExtension singleDatabase = SingleDatabaseBuilder.preparedInstanceWithDefaults(FlywayPreparer.forClasspathLocation("db/testing")) 034 .build(); 035 036 @RegisterExtension 037 public static EmbeddedPgExtension multiDatabase = MultiDatabaseBuilder.preparedInstanceWithDefaults(FlywayPreparer.forClasspathLocation("db/testing")) 038 .build(); 039 040 041 @Test 042 public void testSingleTables() throws Exception { 043 044 DatabaseInfo firstDatabaseInfo = singleDatabase.createDatabaseInfo(); 045 DatabaseInfo secondDatabaseInfo = singleDatabase.createDatabaseInfo(); 046 047 // get the same database on every call 048 assertEquals(firstDatabaseInfo, secondDatabaseInfo); 049 050 // make sure tables exist 051 assertEquals("bar", fetchData(firstDatabaseInfo)); 052 } 053 054 @Test 055 public void testMultiTables() throws Exception { 056 057 DatabaseInfo firstDatabaseInfo = multiDatabase.createDatabaseInfo(); 058 DatabaseInfo secondDatabaseInfo = multiDatabase.createDatabaseInfo(); 059 060 // different databases 061 assertNotEquals(firstDatabaseInfo, secondDatabaseInfo); 062 063 // both database contain the data 064 assertEquals("bar", fetchData(firstDatabaseInfo)); 065 assertEquals("bar", fetchData(secondDatabaseInfo)); 066 } 067 068 private static String fetchData(DatabaseInfo databaseInfo) throws SQLException { 069 try (Connection c = databaseInfo.asDataSource().getConnection(); 070 Statement s = c.createStatement()) { 071 try (ResultSet rs = s.executeQuery("SELECT * FROM foo")) { 072 if (!rs.next()) { 073 return null; 074 } 075 return rs.getString(1); 076 } 077 } 078 } 079}