I have class "Service" and I need to test it methods. I can’t understand how to access the methods of class "Service" from tests.
I tried to do so:
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))
}
}
}
but it does not work
class Service
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
}
The injection framework (google guice) is not started on tests yo your instances will not be injected and that is what you want anyway.
In this case if you want to test your NewsService you probably want to inject a special DAO where you control the outputs so you can test how the NewsService works where there is no news for example.
Just create a NewsService in your test with your test DAO (or you can use 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
}
}
}
If you want to use mockito instead of write custom DAOs you should do something like this
val dao = Mockito.mock(classOf[NewsDAO])
Mockito.when(dao.getNews()).thenReturn(List.empty[News])
val service = new NewsService(dao)
There is syntactic sugar for scala with MockitoSugar