如何使用依赖注入测试 类

How to testing classes with dependency injection

我有 class "Service",我需要测试它的方法。我无法理解如何从测试中访问 class "Service" 的方法。

我试过这样做:

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 服务

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
}

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

在这种情况下,如果您想测试您的 NewsService,您可能想要注入一个特殊的 DAO,您可以在其中控制输出,这样您就可以测试 NewsService 在没有新闻的情况下如何工作。

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

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
    }
 }
}

如果你想使用 mockito 而不是编写自定义 DAO,你应该这样做

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

Scala 有语法糖 MockitoSugar