如何使用依赖注入测试类

时间:2019-04-26 11:19:21

标签: scala playframework scalatest

我有“服务”类,需要测试它的方法。我不明白如何从测试中访问“服务”类的方法。

我试图这样做:

package services

import scala.concurrent.{ExecutionContext, Future}

import com.google.inject.Inject
import models.{News, State}
import org.scalatest.{MustMatchers, WordSpec}

class NewsServiceTest @Inject()(
  newsService: NewsService
)(implicit val ec: ExecutionContext) extends WordSpec with MustMatchers {

  "News controller" must {
    "find all must return sequence with news-object" in {
      val news = News(
        id = 1,
        title = "renamed test title 2",
        short_title = Some("r t s t 2"),
        text = "here is some text about my life and other beautiful things."
      )
      val result: Future[Seq[News]] = newsService.findAll(Some(State.Active))

      result.map(a => a must contain (news))
    }
  }
}

但不起作用

班级服务

class NewsService @Inject()(newsDAO: NewsDAO)(implicit ec: ExecutionContext) {

  def findAll(stateO: Option[State.Value]) = {
    stateO.map(newsDAO.find).getOrElse(newsDAO.findAll)
  }

  def findOne(id: Long) = {
    newsDAO.findOne(id).toEither(InternalDatabaseError.NotFound(classOf[News]))
  }

  def delete(id: Long) = {
    newsDAO.delete(id)
  }

//and other methods
}

1 个答案:

答案 0 :(得分:1)

注入框架(google guice)尚未在测试中启动,您的实例将不会被注入,这仍然是您想要的。

在这种情况下,如果您要测试NewsService,则可能需要在控制输出的位置注入特殊的DAO,以便可以在没有新闻的情况下测试NewsService的工作方式。

只需在您的测试中使用测试DAO创建NewsService(或者您可以使用Mockito)。

class NewsServiceTest extends WordSpec with MustMatchers {
   class EmptyTestDAO extends NewsDAO { 
       def getNews(): List[News] = List.empty

   }


"News controller" must {
   "return an empty list when there is no news" in {
      val service = new NewsService(new EmptyTestDAO)
      service.findAll() shouldBe List.empty
    }
 }
}

如果您要使用模仿而不是编写自定义DAO,则应该执行以下操作

val dao = Mockito.mock(classOf[NewsDAO])
Mockito.when(dao.getNews()).thenReturn(List.empty[News])
val service = new NewsService(dao)

MockitoSugar的scala语法糖