I'm new one in Scala. Currently I'm traing to implement a mock test for traits. Can somebody help me with implementation? I want to mock the methods seasonalityDao.doSomeForB and seasonalityDao.doSomeForB1 inside of the trait SeasonalityServiceImpl and test method hMock.doSomeForF().
Update: I have corrected the code according comments below. In this case, when I try to veryfy mocked methods verify(sMock).doSomeForB() verify(sMock).doSomeForB1(), I receive next error: Wanted but not invoked: seasonalityDao.doSomeForB(); -> at Main$$anonfun$1.apply$mcV$sp(Main.scala:12) Actually, there were zero interactions with this mock.
Here is a code(I have just simplified significant part of project for an example):
import org.scalatest._
import org.mockito.Mockito._
class Main extends FunSuite with SeasonalityServiceComponentImpl with SeasonalityDaoComponent {
test("some test") {
def hMock = mock(classOf[SeasonalityServiceImpl])
def sMock = mock(classOf[SeasonalityDao])
when(sMock.doSomeForB()).thenReturn(Option(2))
when(sMock.doSomeForB1()).thenReturn(10)
verify(sMock).doSomeForB()
verify(sMock).doSomeForB1()
println("With Option " + hMock.doSomeForF())
println("Without Option " + hMock.doSomeForF1())
}
override def seasonalityDao: SeasonalityDao = mock(classOf[SeasonalityDao])
override def seasonalityService: SeasonalityService = mock(classOf[SeasonalityService])
}
trait SeasonalityDaoComponent {
def seasonalityDao: SeasonalityDao
trait SeasonalityDao {
def doSomeForB(): Option[Int]
def doSomeForB1(): Int
}
}
trait SeasonalityServiceComponent {
def seasonalityService: SeasonalityService
trait SeasonalityService {
def doSomeForF(): Option[Int]
def doSomeForF1(): Int
}
}
trait SeasonalityServiceComponentImpl extends SeasonalityServiceComponent {
this: SeasonalityDaoComponent =>
trait SeasonalityServiceImpl extends SeasonalityService {
def doSomeForF(): Option[Int] = {
seasonalityDao.doSomeForB()
}
def doSomeForF1(): Int = {
seasonalityDao.doSomeForB1()
}
}
}
classOf[SeasonalityService]
instead ofseasonality.getClass
. That will use the interface, instead of the anonymous class you return below. – Iulian DragosdMock
but testinghMock
) – Iulian Dragos