我想知道如何在模拟中设置域值或值范围。
trait MyInt{
def getInt():Int
}
trait MyString{
def getName():String
}
我尝试了一些,但没有任何效果。我喜欢定义一个 mockMyInt
来从这个域返回值,(0,100)
并定义一个MyString
trait 来从这个域返回值:{"Dani",Jonny",Jessica",....}
.
我如何使用 scalatest 编写它?
使用 mockito 加上 scalatest
import org.mockito.Mockito._
import org.scalatest.FlatSpec
import org.scalatest.mock.MockitoSugar
import scala.util.Random
class FirstSpec extends FlatSpec with MockitoSugar {
"The mock" should "pick a value from the interval" in {
val mockInt = mock[MyInt]
val mockStr = mock[MyString]
when(mockInt.getInt()).thenReturn(pickOneFrom(1 to 100 toList))
when(mockStr.getName()).thenReturn(pickOneFrom(List("Dani", "Jonny", "Jessica")))
println(mockInt.getInt())
println(mockStr.getName())
}
}
其中pickOne将被定义为
def pickOneFrom[T](domain: List[T]) = domain(Random.nextInt(domain.length))