[英]how to avoid a domain call in unit testing with grails / spock
我有以下幾行代碼
username = username.stripIndent()
user = User."${databaseInstance}".findByUsername(username)
if (user == null){
return "User does not exist"
}
我正在嘗試通過以下方式對該功能進行單元測試:
def setup() {
def mockUser = Mock(User)
myClass.user = mockUser
}
void "userNotFoundGetUserInfo"(){
given:
myClass.databaseInstance = 'X'
_ * mockUser._ >> null
when:
def result = myClass.getUserInfo(username)
then:
result == "User does not exist"
}
但我不斷收到錯誤消息“沒有此類屬性:類mypackage.User為X”
我意識到這是因為我在嘲笑“用戶”對象而不是“用戶”類,所以如何解決我的代碼直接調用域類的事實?
使用Grails內置的@Mock
注釋代替Spock的Mock()
方法。 像這樣:
@Mock(User)
class YourTestSpecification extends Specification {
def setup() {
myClass.user = new User()
}
}
@Mock
用於模擬Grails域類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.