Reputation: 59
package test
import javax.inject._
import org.specs2.mutable._
import play.api.test.Helpers._
import play.api.test._
import play.api.libs.json._
import play.api.cache._
import akka.stream._
import akka.actor._
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.ActorRef
import akka.actor.Props
import akka.pattern.ask
import models.MyWebSocketActor
import scala.collection.mutable.Map
import org.specs2.mock._
import play.api.mvc._
class ValidateMethodTest @Inject() (cache: CacheApi) extends Specification with Mockito {
val system = ActorSystem("MockActorSystem")
val mockMap : Map[ActorRef , String] = Map()
"validator method" should {
"check username key" in {
/*with no username key */
val testMsg1 = Json.parse("""{"message":"Testing Message" ,"conn_status" : 2 , "pub_key":"empty", "target":"all"}""")
val actor1 = system.actorOf(Props[MyWebSocketActor],"actor1")
val actor2 = system.actorOf(Props[MyWebSocketActor],"actor2")
val mockObject1 = new MyWebSocketActor(actor1,actor2,cache,mockMap)
val ( mockReturnMsg, mockReturnCode, mockPub_key) = mockObject1.validate(testMsg1)
mockReturnCode must equalTo(500)
}
}
}
I am doing unit test for a particular method (validate) in class(MyWebSocketActor) that accepts cache as one of its arguments.
So for that , i need to create an instance of Cache . play.api.cache.CacheApi is a trait so can't be instantiated . So i am passing (cache:CacheApi) in this unit class with @Inject. But it gives error message : Can't find a constructor for class play.api.cache.CacheApi .I am using Play 2.5.3 and scala 2.11.x .
Upvotes: 1
Views: 530
Reputation: 8413
You need to mock the CacheApi
(or somehow else create it) rather than using dependency injection.
The Play Documentation has a nice example on how to do this:
import org.specs2.mock._
import org.specs2.mutable._
import java.util._
class ExampleMockitoSpec extends Specification with Mockito {
"MyService#isDailyData" should {
"return true if the data is from today" in {
val mockDataService = mock[DataService]
mockDataService.findData returns Data(retrievalDate = new java.util.Date())
val myService = new MyService() {
override def dataService = mockDataService
}
val actual = myService.isDailyData
actual must equalTo(true)
}
}
}
Upvotes: 1