embedded-postgres icon indicating copy to clipboard operation
embedded-postgres copied to clipboard

Using embedded progress with test frameworks outside of JUnit

Open gregsilin opened this issue 5 years ago • 4 comments

Hi,

We're interested in using the embedded postgres toolkit for our tests, but without JUnit. We are using ScalaTest.

It appears that the library relies heavily on the assumption of integrating with JUnit.

It looks like we should be able to build our own ScalaTest wrappers, unless there is something we're missing from looking at the code.

Could you advise?

gregsilin avatar Dec 12 '19 18:12 gregsilin

Hi,

yes, it is possible to integrate it with other test frameworks. This library is not tied to any specific framework. Just use lower-level api to create an embedded database directly and wrap it to a ScalaTest extension. Check out the SingleInstancePostgresRule and PreparedDbRule classes for inspiration.

Simple example:

// before tests
EmbeddedPostgres postgres = EmbeddedPostgres.start();
DataSource dataSource = postgres.getPostgresDatabase();

// after tests
postgres.close();

Moreover, if the ScalaTest library were defined as optional dependency, then the scala extension would probably be part of this project, similar to the junit4 and junit5 extensions.

tomix26 avatar Dec 13 '19 12:12 tomix26

Hey folks, any breakthrough on this? I am using scala test with multiple sbt modules that need the db up before the tests are executed

Tochemey avatar Nov 30 '20 21:11 Tochemey

@Tochemey This task has a low priority for me. So if you need this feature, help is welcome.

tomix26 avatar Nov 30 '20 21:11 tomix26

As tomix26 mentioned you can simply do start and stop manually inside beforeAll and afterAll: https://www.scalatest.org/scaladoc/1.0/org/scalatest/BeforeAndAfterAll.html#beforeAll%28Map%5BString%2CAny%5D%29,

Example: (Note: I did not run it)

import org.scalatest.{FunSuite, Matchers}

class MyUnitTest extends FunSuite with Matchers {

    private val DB_PORT: Int = 7777
    private var pg: EmbeddedPostgres = null
       
    def beforeAll = {
        pg = EmbeddedPostgres.builder()
                .setPort(DB_PORT)
                .setDataDirectory(Files.createDirectories(Path.of("/tmp").resolve("my_unit_tests").resolve("data")))
                .start()
    }

    test("should return data") {
            val conn = DriverManager.getConnection(String.format("jdbc:postgresql://localhost:%s/postgres?user=postgres&password=", DB_PORT))
            val stmt = conn.createStatement()
            val rs = stmt.executeQuery("SELECT NOW()")
            println("---------------------------------------")
            if (rs.next()) {
                println(rs.getString(1))
            }
    }

    def afterAll = {
      pg.close()
    }
}

prayagupa avatar Jun 15 '21 00:06 prayagupa