我想知道如何在模拟中设置域值或值范围。
trait MyInt{
def getInt():Int
}
trait MyString{
def getName():String
}
我尝试了一些但没有任何作用。
我想定义一个模拟MyInt
来返回(0,100)
的值
和MyString
特征从此域返回值:{"Dani",Jonny",Jessica",....}
。
我怎么能用scalatest来写呢?
答案 0 :(得分:3)
使用mockito plus 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))