这是我的测试类:
import grails.test.mixin.*
import spock.lang.Specification
import spock.lang.Unroll
import spock.lang.*
import groovy.util.logging.Slf4j
@Slf4j
@Mock([PromoRule, PromoCode, SecUser])
@TestFor(PromoService)
class PromoServiceSpec extends Specification {
@Shared testUser
@Shared testCode
@Shared testRule
def setup() {
}
@Unroll
def 'valid promo codes - #user, #code'() {
given:
testRule = new PromoRule(
name : "ZTEST",
receiverAmount : 5,
receiverAmountType : PromoRule.AmountType.DOLLARS,
senderAmount : 0,
senderAmountType : PromoRule.AmountType.DOLLARS,
receiverPointsAmount : null,
receiverPointsAmountType : null,
receiverMaxUse : null,
)
testRule.save(flush:true, failOnError:true)
testUser = new SecUser(
id: 1,
version: 0,
accountExpired: false,
accountLocked: false,
age: 9000,
balance: 100,
dateCreated: new Date(),
emailVerified: true,
enabled: true,
firstName: 'Sir',
lastName: 'Buttocks',
lastUpdated: new Date(),
lockedBalance: 0,
username: "1",
staff: false,
displayName: 'sir_buttocks',
usernameChosen: true,
depositMade: true,
depositOfferRecentlySeen: false,
pin: null
)
testUser.save(flush: true, failOnError: true)
testCode = new PromoCode(
rule : testRule,
code : "3",
senderId : 1,
)
testCode.save(flush:true, failOnError:true)
expect:
service.isValidPromoCode(user, code) == value
where:
user | code || value
testUser | testCode || true
}
}
当我运行此测试时,我得到以下内容:
| Failure: valid promo codes - null, null(skillz.PromoServiceSpec)
| Condition not satisfied:
service.isValidPromoCode(user, code) == value
| | | | | |
| false null null | true
skillz.PromoService@20e0e9d5 false
我尝试了大量不同的配置和布局,所有这些都让我得到一个空指针异常(对于变量本身)或变量的空值。
在static
个变量上执行所有定义并未改变任何内容,与使用@Shared
的结果相同。
我也尝试过模拟这些,但在尝试为类执行.Mock()时总是会遇到null异常...
谢谢!
答案 0 :(得分:13)
我不确定你要在这里实现什么,但{<1}}块在之前评估(其余的)方法首先进入,并且当时,您的共享变量为null。您必须提前设置它们,例如在where
(不是setupSpec
)方法中。