Scala/Play: Test class: reading a custom configuration file from the /conf folder

262 Views Asked by At

Using Play 2.7. In a test class, I want to test a service that reads the configuration (properties) file conf/fun.conf.

I could not find any example how to carry out this feat. I have looked at the Play documentation and also questions here, but found nothing.

The service I wrote gets Configuration through injection:

class MyFunService @Inject() (config: Configuration) extends FunService {

    override def getValue(key: String) = config.get[String](key)

}

I want to call this service from a test:

class FunSpec(implicit ee: ExecutionEnv) extends Specification {

  sequential

  "The FunService" should {

    "retrieve a value" in new WithApplication() {

      //Oops! Does not actually read the conf file...
      val env = play.api.Environment.simple()
      val config = play.api.Configuration.load(env)

      //...so getting an Exception here.
      val f = Future(new MyFunService(config).getValue("fun_stuff"))

      f must beEqualTo("having_fun").await(retries = 0, timeout = 5.seconds)
    }
  }
}
1

There are 1 best solutions below

0
Noam On

I'm using this code to read test resources

import com.google.common.base.Charsets.UTF_8
import com.google.common.io.Resources

object ResourceFileSupport {
  def read(file: String) =
    Resources.toString(
      Option( this.getClass.getClassLoader.getResource(file) ).getOrElse {
        throw new IllegalArgumentException(s"resource $file not found in classpath.")
      }, UTF_8)
}