Specs2 Steps not executing in order - scala

I am attempting to execute a Specification with multiple tests that all run within the same Play application and not a separate application for each test.
As such I have the following code which should print:
Play app started
[info] PlayRunningImmutableSpec
[info]
[info] + 200 status expected
[info]
[info] + 404 status expected
Play app stopped
but instead prints:
Play app started
Play app stopped
[info] PlayRunningImmutableSpec
[info]
[info]
[info] ! 200 status expected
[error] ConnectException: : Connection refused: /127.0.0.1:19001 to http://127.0.0.1:19001/
I am using Typesafe Activator 1.2.10 which includes Play 2.3.3 and Specs2 2.3.12
What is wrong with the following code, and what would work instead?
import org.specs2.Specification
import org.specs2.execute.Result
import org.specs2.specification.Step
import org.specs2.time.NoTimeConversions
import play.api.Play
import play.api.Play.current
import play.api.http.{HeaderNames, HttpProtocol, Status}
import play.api.libs.ws.WS
import play.api.test._
class PlayRunningImmutableSpec extends Specification with NoTimeConversions with PlayRunners with HeaderNames with Status with HttpProtocol with DefaultAwaitTimeout with ResultExtractors with Writeables with RouteInvokers with FutureAwaits {
override def is = s2"""
${Step(beforeAll)}
200 status expected $e1
404 status expected $e2
${Step(afterAll)}
"""
def e1: Result = {
await(WS.url(s"http://127.0.0.1:${Helpers.testServerPort}").get()).status === 200
}
def e2: Result = {
await(WS.url(s"http://127.0.0.1:${Helpers.testServerPort}/missing").get()).status === 404
}
lazy val app = FakeApplication()
private def beforeAll = {
Play.start(app)
println("Play app started")
}
private def afterAll = {
Play.stop()
println("Play app stopped")
}
}
EDIT:
I realised my error was in the use the play.api.Play.start method and now have a simple trait to handle one startup and shutdown:
trait PlayServerRunning extends SpecificationLike {
override def map(fs: => Fragments): Fragments = Step(beforeAll) ^ fs ^ Step(afterAll)
private lazy val server = TestServer(Helpers.testServerPort)
private def beforeAll = {
server.start()
}
private def afterAll = {
server.stop()
}
}

That's on propose. Tests are executed in parallel (with implementation details according execution context).
If your tests need to be sequential, you must annotate in this way. e.g.:
"X" should {
sequential
"exp1" in { ... }
"exp2" in { ... }
}

Related

Scala Play + Slick: How to inject dependencies to Spec tests?

I'm using Scala Play 2.7.x (the project is available here Play-Silhouette-Seed) and would like to test my daos. I have put together this simple one first to check what's the "new pattern" for testing play + slick + guice in 2.7.x:
package models.daos
import java.util.UUID
import org.specs2.mock._
import org.specs2.mutable._
import utils.AwaitUtil
import javax.inject.Inject
import models.generated.Tables.LoginInfoRow
class LoginInfoDaoSpec #Inject() (loginInfoDao: LoginInfoDao) extends Specification with Mockito with AwaitUtil {
"Creating a new LoginInfo" should {
"save it in the empty database" in {
loginInfoDao.create(LoginInfoRow(0, UUID.randomUUID().toString, UUID.randomUUID().toString))
loginInfoDao.findAll.size should beEqualTo(1)
}
}
}
Unfortunately, the guice dependency LoginInfoDao is not being provided to my test and then I get the error:
[play-silhouette-seed] $ testOnly models.daos.LoginInfoDaoSpec
[info] Done compiling.
[error] Can't find a suitable constructor with 0 or 1 parameter for class models.daos.LoginInfoDao
[info] ScalaTest
[info] Run completed in 1 second, 966 milliseconds.
[info] Total number of tests run: 0
[info] Suites: completed 0, aborted 0
[info] Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
[info] No tests were executed.
[error] Error: Total 1, Failed 0, Errors 1, Passed 0
How do I get guice loading the needed modules for my test-cases?
A module is defined as:
class SilhouetteModule extends AbstractModule with ScalaModule {
override def configure() {
// ...
bind[LoginInfoDao].to[LoginInfoDaoImpl]
// ...
}
}
and I have an application.test.conf available defined as:
include "application.conf"
slick.dbs {
default {
profile="slick.jdbc.MySQLProfile$"
db.driver="com.mysql.cj.jdbc.Driver"
db.url="jdbc:mysql://localhost:3306/mytestdb?useUnicode=true&searchpath=public&serverTimezone=CET"
db.user="dev"
db.password="12345"
}
}
You should use another database for testing, H2 is the common choice.
class Module extends AbstractModule with ScalaModule {
...
}
With that name you need to let play know there is a Module to load, if you call it Module, it automatically know what to load and should work just fine (if you only need 1 module in testing)
If that doesn't work let me know

Specs2: how to test a class with more than one injected dependency?

Play 2.4 app, using dependency injection for service classes.
I found that Specs2 chokes when a service class being tested has more than one injected dependency. It fails with "Can't find a constructor for class ..."
$ test-only services.ReportServiceSpec
[error] Can't find a constructor for class services.ReportService
[error] Error: Total 1, Failed 0, Errors 1, Passed 0
[error] Error during tests:
[error] services.ReportServiceSpec
[error] (test:testOnly) sbt.TestsFailedException: Tests unsuccessful
[error] Total time: 2 s, completed Dec 8, 2015 5:24:34 PM
Production code, stripped to bare minimum to reproduce this problem:
package services
import javax.inject.Inject
class ReportService #Inject()(userService: UserService, supportService: SupportService) {
// ...
}
class UserService {
// ...
}
class SupportService {
// ...
}
Test code:
package services
import javax.inject.Inject
import org.specs2.mutable.Specification
class ReportServiceSpec #Inject()(service: ReportService) extends Specification {
"ReportService" should {
"Work" in {
1 mustEqual 1
}
}
}
If I remove either UserService or SupportService dependency from ReportService, the test works. But obviously the dependencies are in the production code for a reason. Question is, how do I make this test work?
Edit: When trying to run the test inside IntelliJ IDEA, the same thing fails, but with different messages: "Test framework quit unexpectedly", "This looks like a specs2 exception..."; see full output with stacktrace. I opened a Specs2 issue as instructed in the output, though I have no idea if the problem is in Play or Specs2 or somewhere else.
My library dependencies below. (I tried specifying Specs2 version explicitly, but that didn't help. Looks like I need specs2 % Test as is, for Play's test classes like WithApplication to work.)
resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases"
libraryDependencies ++= Seq(
specs2 % Test,
jdbc,
evolutions,
filters,
"com.typesafe.play" %% "anorm" % "2.4.0",
"org.postgresql" % "postgresql" % "9.4-1205-jdbc42"
)
There is limited support for dependency injection in specs2, mostly for execution environments or command-line arguments.
There is nothing preventing you from just using a lazy val and your favourite injection framework:
class MySpec extends Specification with Inject {
lazy val reportService = inject[ReportService]
...
}
With Play and Guice, you could have a test helper such as this:
import play.api.inject.guice.GuiceApplicationBuilder
import scala.reflect.ClassTag
trait Inject {
lazy val injector = (new GuiceApplicationBuilder).injector()
def inject[T : ClassTag]: T = injector.instanceOf[T]
}
If you really need runtime dependency injection, then it's better to use Guice loading, I guess:
package services
import org.specs2.mutable.Specification
import scala.reflect.ClassTag
import com.google.inject.Guice
// Something you'd like to share between your tests
// or maybe not
object Inject {
lazy val injector = Guice.createInjector()
def apply[T <: AnyRef](implicit m: ClassTag[T]): T =
injector.getInstance(m.runtimeClass).asInstanceOf[T]
}
class ReportServiceSpec extends Specification {
lazy val reportService: ReportService = Inject[ReportService]
"ReportService" should {
"Work" in {
reportService.foo mustEqual 2
}
}
}
Alternatively you can implement Inject object as
import scala.reflect.ClassTag
import play.api.inject.guice.GuiceApplicationBuilder
object Inject {
lazy val injector = (new GuiceApplicationBuilder).injector()
def apply[T : ClassTag]: T = injector.instanceOf[T]
}
It depends whether you want to use Guice directly, or thru play wrappers.
Looks like you are out of luck ATM: The comment says
Try to create an instance of a given class by using whatever constructor is available and trying to instantiate the first parameter recursively if there is a parameter for that constructor.
val constructors = klass.getDeclaredConstructors.toList.filter(_.getParameterTypes.size <= 1).sortBy(_.getParameterTypes.size)
i.e. Specs2 doesn't provide own DI out-of-the box,
Or you can reimplement the functionality yourself, if Guice isn't working for you.
App code:
package services
import javax.inject.Inject
class ReportService #Inject()(userService: UserService, supportService: SupportService) {
val foo: Int = userService.foo + supportService.foo
}
class UserService {
val foo: Int = 1
}
class SupportService {
val foo: Int = 41
}
Test code
package services
import org.specs2.mutable.Specification
import scala.reflect.ClassTag
import java.lang.reflect.Constructor
class Trick {
val m: ClassTag[ReportService] = implicitly
val classLoader: ClassLoader = m.runtimeClass.getClassLoader
val trick: ReportService = Trick.createInstance[ReportService](m.runtimeClass, classLoader)
}
object Trick {
def createInstance[T <: AnyRef](klass: Class[_], loader: ClassLoader)(implicit m: ClassTag[T]): T = {
val constructors = klass.getDeclaredConstructors.toList.sortBy(_.getParameterTypes.size)
val constructor = constructors.head
createInstanceForConstructor(klass, constructor, loader)
}
private def createInstanceForConstructor[T <: AnyRef : ClassTag]
(c: Class[_], constructor: Constructor[_], loader: ClassLoader): T = {
constructor.setAccessible(true)
// This can be implemented generically, but I don't remember how to deal with variadic functions
// generically. IIRC even more reflection.
if (constructor.getParameterTypes.isEmpty)
constructor.newInstance().asInstanceOf[T]
else if (constructor.getParameterTypes.size == 1) {
// not implemented
null.asInstanceOf[T]
} else if (constructor.getParameterTypes.size == 2) {
val types = constructor.getParameterTypes.toSeq
val param1 = createInstance(types(0), loader)
val param2 = createInstance(types(1), loader)
constructor.newInstance(param1, param2).asInstanceOf[T]
} else {
// not implemented
null.asInstanceOf[T]
}
}
}
// NB: no need to #Inject here. The specs2 framework does it for us.
// It sees spec with parameter, and loads it for us.
class ReportServiceSpec (trick: Trick) extends Specification {
"ReportService" should {
"Work" in {
trick.trick.foo mustEqual 2
}
}
}
And that expectedly fails with
[info] ReportService should
[error] x Work
[error] '42' is not equal to '2' (FooSpec.scala:46)
If you don't need runtime dependency injection, then it's better to use cake pattern, and forget reflection all-together.
My colleague suggested a "low-tech" workaround. In the test, instantiate service classes with new:
class ReportServiceSpec extends Specification {
val service = new ReportService(new UserService, new SupportService)
// ...
}
This also works:
class ReportServiceSpec #Inject()(userService: UserService) extends Specification {
val service = new ReportService(userService, new SupportService)
// ...
}
Feel free to post more elegant solutions. I've yet to see a simple DI solution that works (with Guice, Play's default).
Does anyone else find it curious that Play's default test framework does not play well with Play's default DI mechanism?
Edit: In the end I went with an "Injector" test helper, almost the same as what Eric suggested:
Injector:
package testhelpers
import play.api.inject.guice.GuiceApplicationBuilder
import scala.reflect.ClassTag
/**
* Provides dependency injection for test classes.
*/
object Injector {
lazy val injector = (new GuiceApplicationBuilder).injector()
def inject[T: ClassTag]: T = injector.instanceOf[T]
}
Test:
class ReportServiceSpec extends Specification {
val service = Injector.inject[ReportService]
// ...
}

Functional Tests in Play 2.4.6 when using compile time DI

I'm using Play 2.4.6 with compile time dependency injection and ScalaTest. The controller's constructor has few parameters, and in an ApplicationLoader I create it.
Here is the code:
class BootstrapLoader extends ApplicationLoader {
def load(context: Context) = {
new AppComponents(context).application
}
}
class AppComponents(context: Context) extends BuiltInComponentsFromContext(context) with NingWSComponents {
lazy val router = new Routes(httpErrorHandler, authenticationController, applicationController, assets)
lazy val applicationController = new controllers.Application()
lazy val authenticationController = new controllers.Authentication()(configuration, wsApi.client)
lazy val assets = new controllers.Assets(httpErrorHandler)
}
class Authentication(implicit configuration: Configuration, val ws: WSClient) extends Controller {
def login = Action { implicit request =>
Unauthorized(s"${redirectUrl}")
}
}
class AuthenticationSpec extends PlaySpec with OneAppPerSuite {
implicit val configuration: Configuration = app.configuration
implicit val wsClient: WSClient = WS.client(app)
"when user not logged-in" should {
"return Status code Unauthorized(401) with redirect url" in {
1 mustEqual 2
}
}
}
When I'm running the test I'm getting the following error:
[info] Exception encountered when attempting to run a suite with class name: controllers.AuthenticationSpec *** ABORTED ***
[info] com.google.inject.ProvisionException: Unable to provision, see the following errors:
[info]
[info] 1) Could not find a suitable constructor in controllers.Authentication. Classes must have either one (and only one) constructor annotated with #Inject or a zero-argument constructor that is not private.
[info] at controllers.Authentication.class(Authentication.scala:19)
[info] while locating controllers.Authentication
[info] for parameter 1 at router.Routes.<init>(Routes.scala:35)
[info] while locating router.Routes
[info] while locating play.api.test.FakeRouterProvider
[info] while locating play.api.routing.Router
[info]
[info] 1 error
[info] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025)
[info] at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
[info] at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:321)
[info] at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:316)
[info] at play.api.Application$class.routes(Application.scala:112)
[info] at play.api.test.FakeApplication.routes(Fakes.scala:197)
[info] at play.api.Play$$anonfun$start$1.apply$mcV$sp(Play.scala:90)
[info] at play.api.Play$$anonfun$start$1.apply(Play.scala:87)
[info] at play.api.Play$$anonfun$start$1.apply(Play.scala:87)
[info] at play.utils.Threads$.withContextClassLoader(Threads.scala:21)
FakeApplication use GuiceApplicationBuilder, which of course does not work.
What should I do to run such tests?
Thanks
override implicit lazy val app = new BootstrapLoader().load(
ApplicationLoader.createContext(
new Environment(
new File("."), ApplicationLoader.getClass.getClassLoader, Mode.Test)))
It works in Play 2.5.1
You are getting an error because the tests are not even able to start a application. That is happening because you are using Dependency Injection in your controllers (as the error message suggests) and you need to declare them as classes, instead of as objects. As you can see at the docs:
package controllers
import play.api.mvc._
class Application extends Controller {
def index = Action {
Ok("It works!")
}
}
If your controller has some dependency to be injected, you should use the #Inject annotation in your controller constructor (again, please see the docs). Per instance:
package controllers
import play.api.mvc._
import play.api.libs.ws._
import javax.inject._
class Application #Inject() (ws: WSClient) extends Controller {
// ...
}
You can also read the Compile Time Dependency Injection docs if you are using it instead of runtime DI.
If you use specs2 you can do it. see http://loicdescotte.github.io/posts/play24-compile-time-di/
But you loose the nice api.
Scalatest / scalatest-plus has done something funky with the DI (guice) :(
I'm facing the same problem as you. I don't have a satisfying solution, the following is a mere workaround:
I ended up putting
implicit def client:WSClient = NingWSClient()
in my WithApplicationLoader class
I also found https://github.com/leanovate/play-mockws which allows you to mock ws calls. But that's not what we want here.
my guess would be that the OneAppPerSuite trait isn't using your custom application loader. you may need to override the application construction that comes from that trait and make it use your custom loader.
looks like there is an example using scalatest here: http://mariussoutier.com/blog/2015/12/06/playframework-2-4-dependency-injection-di/

Using FunSuite to test Spark throws NullPointerException

I would like to use FunSuite to test my Spark jobs by extending FunSuite with a new function, called localTest, that runs a test with a default SparkContext:
class SparkFunSuite extends FunSuite {
def localTest(name : String)(f : SparkContext => Unit) : Unit = {
val conf = new SparkConf().setAppName(name).setMaster("local")
val sc = new SparkContext(conf)
try {
this.test(name)(f(sc))
} finally {
sc.stop
}
}
}
Then I can add tests easily to my testing suites:
class MyTestSuite extends SparkFunSuite {
localTest("My Spark test") { sc =>
assertResult(2)(sc.parallelize(Seq(1,2,3)).filter(_ <= 2).map(_ + 1).count)
}
}
The problem is that when I run the tests I get a NullPointerException:
[info] MyTestSuite:
[info] - My Spark test *** FAILED ***
[info] java.lang.NullPointerException:
[info] at org.apache.spark.SparkContext.defaultParallelism(SparkContext.scala:1215)
[info] at org.apache.spark.SparkContext.parallelize$default$2(SparkContext.scala:435)
[info] at MyTestSuite$$anonfun$1.apply(FunSuiteTest.scala:24)
[info] at MyTestSuite$$anonfun$1.apply(FunSuiteTest.scala:23)
[info] at SparkFunSuite$$anonfun$localTest$1.apply$mcV$sp(FunSuiteTest.scala:13)
[info] at SparkFunSuite$$anonfun$localTest$1.apply(FunSuiteTest.scala:13)
[info] at SparkFunSuite$$anonfun$localTest$1.apply(FunSuiteTest.scala:13)
[info] at org.scalatest.Transformer$$anonfun$apply$1.apply$mcV$sp(Transformer.scala:22)
[info] at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
[info] at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
[info] ...
What is causing the NullPointerException? Is my way to use Spark not correct in this context?
I'm using Scala 2.10.4 with spark-core 1.0.2 and scalatest 2.2.2.
If you are running SparkContexts in more than one class, make sure that you put parallelExecution in Test := false in your build.sbt. I was running into the problem when I ran the command: sbt test. I would either get a NPE or a PARSING_ERROR caused by multiple SparkContexts running in the JVM.
The reason why this wasn't working is that I misused FunSuite.test. This method registers a new test when it is called, that is when FunSuite is constructed. The test will then be called when tests are run. But my localTest does some actions before and after calling FunSuite.test. In particular, after register the test with this.test(name)(f(sc)), it stops the SparkContext. When the test is called, sc is stopped and that causes the NullPointerException on the taskScheduler field of SparkContxt. The correct way to use FunSuite is:
import org.scalatest.FunSuite
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
class SparkFunSuite extends FunSuite {
def localTest(name : String)(f : SparkContext => Unit) : Unit = {
this.test(name) {
val conf = new SparkConf()
.setAppName(name)
.setMaster("local")
.set("spark.default.parallelism", "1")
val sc = new SparkContext(conf)
try {
f(sc)
} finally {
sc.stop()
}
}
}
}
class MyTestSuite extends SparkFunSuite {
localTest("My Spark test") { sc =>
assertResult(2)(sc.parallelize(Seq(1,2,3)).filter(_ <= 2).map(_ + 1).count)
}
}

In Play 2.2, Spec2 tests, I get Configuration error[Cannot connect to database [default]]

I am using Scala Spec2 in Play Framework version 2.2 application. When I run the tests, I get following errors:
$ test-only ApplicationSpec
Mode is Test, Loading: application.test.conf
Create schema
Populate the application schema...
Stopping the application...
Stopping the application...
Stopping the application...
[info] ApplicationSpec
[info] Application should
[info] + send 404 on a bad request
[info] ! render the login page
[error] anon$1: Configuration error[Cannot connect to database [default]] (Configuration.scala:92)
[error] play.api.Configuration$.play$api$Configuration$$configError(Configuration.scala:92)
[error] play.api.Configuration.reportError(Configuration.scala:570)
[error] play.api.db.BoneCPPlugin$$anonfun$onStart$1.apply(DB.scala:252)
[error] play.api.db.BoneCPPlugin$$anonfun$onStart$1.apply(DB.scala:243)
[error] play.api.db.BoneCPPlugin.onStart(DB.scala:243)
[error] play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:88)
[error] play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:88)
[error] play.api.Play$$anonfun$start$1.apply$mcV$sp(Play.scala:88)
[error] play.api.Play$$anonfun$start$1.apply(Play.scala:88)
[error] play.api.Play$$anonfun$start$1.apply(Play.scala:88)
[error] play.utils.Threads$.withContextClassLoader(Threads.scala:18)
[error] play.api.Play$.start(Play.scala:87)
[error] play.api.test.PlayRunners$class.running(Helpers.scala:44)
[error] play.api.test.Helpers$.running(Helpers.scala:364)
[error] ApplicationSpec$$anonfun$1$$anonfun$apply$12.apply(ApplicationSpec.scala:25)
[error] ApplicationSpec$$anonfun$1$$anonfun$apply$12.apply(ApplicationSpec.scala:25)
MockGlobal.scala contains following code:
object MockGlobal extends GlobalSettings {
override def onStart(app: Application) {
super.onStart(app)
// check if the database is already setup
implicit val a = app
if (isDatabaseEmpty(app)) {
println("Create schema")
FixtureUtils.populateSchema
println("Pouplate fixtures ")
FixtureUtils.GoldData.populateFixtures
}
}
def isDatabaseEmpty(app: Application) = {
implicit val a = app
DB.withSession { implicit session =>
val lst = MTable.getTables("users").list()
lst.isEmpty
}
}
override def onLoadConfig(config: Configuration,
path: File, classloader: ClassLoader,
mode: Mode.Mode): Configuration = {
val configfile = s"application.${mode.toString.toLowerCase}.conf"
println(s"Mode is ${mode.toString}, Loading: ${configfile}")
val modeSpecificConfig = config ++ Configuration(
ConfigFactory.load(configfile))
super.onLoadConfig(modeSpecificConfig, path, classloader, mode)
}
override def onStop(app: Application) {
println("Stopping the application...")
}
}
TestApplication.scala contains following code:
object TestApplication {
val log = play.Logger.of("application")
lazy val app = FakeApplication(withGlobal = Some(MockGlobal))
}
ApplicationSpec.scala contains following code:
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.test._
import play.api.test.Helpers._
import models.User
import models.Users
import fixtures.TestApplication
import fixtures.FixtureUtils
/**
* Add your spec here.
* You can mock out a whole application including requests, plugins etc.
* For more information, consult the wiki.
*/
#RunWith(classOf[JUnitRunner])
class ApplicationSpec extends Specification {
"Application" should {
"send 404 on a bad request" in new WithApplication(TestApplication.app) {
route(FakeRequest(GET, "/boum")) must beNone
}
"render the login page" in running(TestApplication.app) {
val home = route(FakeRequest(GET, "/")).get
// must redirect to login page
status(home) must equalTo(SEE_OTHER)
val x = redirectLocation(home).map { location =>
location must equalTo("/login")
val loginpage = route(FakeRequest(GET, "/login")) map { result =>
status(result) must equalTo(OK)
contentType(result) must beSome.which(_ == "text/html")
contentAsString(result) must contain("Apps: Login")
}
}
x must beSome
}
}
}
I have seen similar error reported here:
https://github.com/playframework/playframework/issues/1667
https://groups.google.com/forum/#!topic/play-framework/apKy2qVUttw
I tried adding following line to build.sbt to not fork for each test. This didn't help either:
Keys.fork in (Test) := false
Note two things:
Actual error: Configuration error[Cannot connect to database [default]] (Configuration.scala:92)
This appears three times Stopping the application...
What can I do to solve this issue ?
I was trying to avoid creating a new application each time a test is run, so I used:
lazy val app = FakeApplication(withGlobal = Some(MockGlobal))
However this is the wrong approach. For a forked test, once it has finished, the application is stopped, thereby making it unavailable for other tests. This is the reason I was getting database connection errors in all but the first test that executed.
I changed the spec test definition
from this: in new WithApplication(TestApplication.app)
to this: in running(FakeApplication(withGlobal = Some(MockGlobal)))
Here is how it looks now:
"render the login page" in running(FakeApplication(withGlobal = Some(MockGlobal))) {
val home = route(FakeRequest(GET, "/")).get
// must redirect to login page
status(home) must equalTo(SEE_OTHER)
val x = redirectLocation(home).map { location =>
location must equalTo("/login")
val loginpage = route(FakeRequest(GET, "/login")) map { result =>
status(result) must equalTo(OK)
contentType(result) must beSome.which(_ == "text/html")
contentAsString(result) must contain("Apps: Login")
}
}
x must beSome
}
Now all the testcases are working fine. I am not seeing any error Configuration error[Cannot connect to database [default]].