【发布时间】:2019-03-10 15:15:41
【问题描述】:
我有一个HelperMethod 课程。
class HelperMethods {
def getUniqueID(): UUID = {
UUID.randomUUID()
}
def bucketIDFromEmail(email:String): Int = {
val bucketID= email(0).toInt
println("returning id "+bucketID+" for name "+email)
bucketID
}
}
还有一个object,它有一个HelperMethods 的实例
package object utilities{
private val helper = new HelperMethods()
def getUniqueID(): UUID = helper.getUniqueID()
def bucketIDFromEmail(email:String): Int = helper.bucketIDFromEmail(email)
}
我编写了一个规范来测试我的模拟是否正常工作。
class UserControllerUnitSpec extends PlaySpec {
val mockHelperMethods = mock(classOf[HelperMethods])
when(mockHelperMethods.getUniqueID()).thenReturn(UUID.fromString("87ea52b7-0a70-438f-81ff-b69ab9e57210"))
when(mockHelperMethods.bucketIDFromEmail(ArgumentMatchers.any[String])).thenReturn(1)
"mocking helper class " should {
"work" in {
val bucketId = utilities.bucketIDFromEmail("t@t.com")
println("user keys are " + userKeys)
val id: UUID = utilities.getUniqueID()
println("got id " + userKeys)
bucketId mustBe 1
id mustBe UUID.fromString("87ea52b7-0a70-438f-81ff-b69ab9e57210")
}
}
}
测试失败,原因为116 was not equal to 1。这对应于线
bucketId mustBe 1 在规范中。我可以看到打印returning id 116 for name t@t.com。我不应该看到它,因为我试图模拟这门课。我怀疑这可能是因为 utilities 对象是在规范中的声明 val mockHelperMethods = mock(classOf[HelperMethods]) 之前创建的。
问题 2- 有没有办法模拟 HelperMethods 并使 utilities 使用模拟类?
【问题讨论】: