我正在使用Scala,Play Framework開發web應用程序。我需要用自定義操作來測試控制器。請看代碼:函數的模擬函數參數
package controllers.helpers
import play.api.mvc.{ActionBuilder, Request, Result}
import scala.concurrent.Future
class CustomAction extends ActionBuilder[Request] {
override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
// do some stuff
block(request)
}
}
package controllers
import javax.inject.Singleton
import play.api.mvc.Controller
@Singleton
class SomeController @Inject() (customAction: CustomAction
) extends Controller {
def foo() = customAction(parse.json) { implicit request =>
// do some stuff and create result
}
}
下面你可以找到測試類的代碼。我用Specs2和我上線了org.mockito.exceptions.misusing.InvalidUseOfMatchersException
與customeActionMock.invokeBlock(any[Request[_]], any[(Request[_]) => Future[Result]]) returns mock[Future[Result]]
package controllers
import controllers.helpers.CustomAction
import org.specs2.mock.Mockito
import play.api.mvc.{Request, Result}
import play.api.test.{FakeHeaders, FakeRequest, PlaySpecification}
import scala.concurrent.Future
class SomeControllerSpec extends PlaySpecification with Mockito {
private val customeActionMock = mock[CustomAction]
customeActionMock.invokeBlock(any[Request[_]], any[(Request[_]) => Future[Result]]) returns mock[Future[Result]] //this doesn't work, exception is thrown there
"SomController" should {
"respond Ok on valid request" in {
val result = new UserController(customeActionMock).foo()(FakeRequest())
status(result) shouldEqual OK
}
}
}
我明白,我嘲笑CustomAction
正確的block
參數。有人可以幫助我做到這一點嗎?
您設置您的測試的方式,結果值''會保留模擬值'mock [Future [Result]]''。換句話說,如果你嘲笑應該運行'block'的代碼,你的行爲中的代碼將不會運行..我想我不會模仿CustomAction,但是它會成爲測試的一部分。 – rethab