Mark & run integration unit tests with SBT and Scala

It is a good practice to write integration unit tests for your services and integrate them in your CI workflow. Such integration tests boosts the confidence of your application quality especially when it needs to be deployed in an environment where it has to talk to numerous other external services. In this regard, I wanted to write such integration tests for one of my scala project which uses SBT as a build tool.

I will just list down the steps that are needed to get this up and running!

First, in your build.sbt define the configuration and settings that can help sbt to differentiate between your integration unit tests and normal unit tests.

 1// Command to run integration tests, so here to run the integration tests we use -> sbt integration-test
 2addCommandAlias("integration-test", "Integration/testOnly -- -n integrationTest")
 3
 4lazy val IntegrationTest = config("integration").extend(Test)
 5
 6lazy val root = Project(base = file("."))
 7  .configs(IntegrationTest)
 8  .settings(
 9    IntegrationTest / parallelExecution := false, // We do not want Integration tests to execute parallely!
10    Test / testOptions += Tests.Argument(TestFrameworks.ScalaTest, "-l", "integrationTest"), // Exclue the Inegration tests from the normal unit tests
11    // Include integration tests, by nullifying the above option
12    IntegrationTest / testOptions := Seq.empty,
13  )
14  .settings(
15    // Enable integration tests
16    inConfig(IntegrationTest)(Defaults.testTasks)
17  )

We need to do a few more steps before we can get the whole thing up and running. We need to define an object that extends the Tag for your testing framework. So in my case I use scalatest and for me it would look like:

1import org.scalatest.Tag
2object IntegrationTest extends Tag("integrationTest")

After this, we can now start writing our test classes and tag them as IntegrationTest:

1  test("integration testing with sbt", IntegrationTest) {
2    Future {
3      println("ALLES OKAY *************************************** ")
4      assert(true)
5    }
6  }

Now you can run your integration tests separately for your project as below:

1sbt integration-test