Add different configuration file for test
When writing unit test in sbt project it is very common to use a different configuration rather than the default one (application.conf) that resides in:
In order to avoid this and user a different configuration file for test we can add a test configuration in:
and can name that either application.conf or any of our choice. Currently let’s name it test.conf. So our test configuration will be at:
NOTE: In test.conf we should use the following:
<YOUR TEST CONFIGURATION SETTINGS>
Use test configuration when running test
Usually when running test from IDE we can use -Dconfig.file or -Dconfig.resource in edit configuration of test. If we run test using RUN icon from IDE then it selects the test configuration and run the test, but for targeted class it still uses the application.conf. So what can we do now? In order to do that let’s follow the following steps:
- Open build.sbt of the project for which you write the test. Not the one in the root directory.
- Add the following lines:
fork in Test := true //it will allow to apply extra settings to Test
javaOptions in Test += “-Dconfig.resource=test.conf” //here we will apply extra setting
Now if you try to run the test from IDE using the RUN icon, then you will see that the test.conf is not used for the targeted class. So is there anything wrong we did, or is our configuration wrong? The answer is NO. When we use RUN icon then IDE check the configuration settings from its edit configuration form, that is why our test configuration is not picked even we add that to build.sbt.
So what we need to do in order to tell test to pick our test configuration? Simply run the command:
Now you will see that while running the test our test configuration is being picked.
Please remember, sbt test runs all the test in test directory. You can check my article about how to run Scala test using sbt command.
That’s it, enjoy your unit tests 🙂