我對用 groovy 撰寫的測驗有問題(使用 Spock 作為框架)。當我嘗試在then塊中獲取屬性然后在互動中使用它時,我收到No such property: updatedValue for class: my.test.class.MyTestClass了與事件發布者的互動。誰能告訴這是為什么?
class MyTestClass extends Specification {
@Autowired
private MyClass sut
@Autowired
private MyClassRepository myClassRepository
@SpringBean
private EventPublisher eventPublisher = Mock()
def "Should do something"() {
given:
//some data
def someId = "someId"
def event = new SomeEventObject()
when:
sut.handle(event)
then:
def updatedValue = myClassRepository.findTestClass(someId)
updatedTestClass.cash == 100
1 * eventPublisher.publishEvent(new SomeNextEvent(updatedValue))
}
}
uj5u.com熱心網友回復:
您遇到了 Spock 魔法的副作用。
你的方法基本上變成了這個:
public void $spock_feature_0_0() {
org.spockframework.runtime.ErrorCollector $spock_errorCollector = org.spockframework.runtime.ErrorRethrower.INSTANCE
org.spockframework.runtime.ValueRecorder $spock_valueRecorder = new org.spockframework.runtime.ValueRecorder()
java.lang.Object someId = 'someId'
java.lang.Object event = new apackage.SomeEventObject()
this.getSpecificationContext().getMockController().enterScope()
this.getSpecificationContext().getMockController().addInteraction(new org.spockframework.mock.runtime.InteractionBuilder(25, 9, '1 * eventPublisher.publishEvent(new SomeNextEvent(updatedValue))').setFixedCount(1).addEqualTarget(eventPublisher).addEqualMethodName('publishEvent').setArgListKind(true, false).addEqualArg(new apackage.SomeNextEvent(updatedValue)).build())
sut.handle(event)
this.getSpecificationContext().getMockController().leaveScope()
java.lang.Object updatedValue = myClassRepository.findTestClass(someId)
try {
org.spockframework.runtime.SpockRuntime.verifyCondition($spock_errorCollector, $spock_valueRecorder.reset(), 'updatedTestClass.cash == 100', 23, 13, null, $spock_valueRecorder.record($spock_valueRecorder.startRecordingValue(3), $spock_valueRecorder.record($spock_valueRecorder.startRecordingValue(1), $spock_valueRecorder.record($spock_valueRecorder.startRecordingValue(0), updatedTestClass).cash) == $spock_valueRecorder.record($spock_valueRecorder.startRecordingValue(2), 100)))
}
catch (java.lang.Throwable throwable) {
org.spockframework.runtime.SpockRuntime.conditionFailedWithException($spock_errorCollector, $spock_valueRecorder, 'updatedTestClass.cash == 100', 23, 13, null, throwable)}
finally {
}
this.getSpecificationContext().getMockController().leaveScope()
}
如果仔細觀察,您會發現互動定義在塊之前移動了when,但findTestClass()呼叫留在了后面。這就是為什么您會收到丟失的屬性例外。
解決方案是將查找移動到given塊,或者如果不可能,則使用引數捕獲,然后再檢查。
given:
def capturedEvent
when:
...
then:
1 * eventPublisher.publishEvent(_) >> { capturedEvent = it[0} }
and:
def updatedValue = myClassRepository.findTestClass(someId)
capturedEvent instanceof SomeNextEvent
capturedEvent.value == updatedValue
您可以通過單擊在groovy Web 控制臺中自己查看轉換后的代碼Inspect AST。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/399185.html
下一篇:無法從配置服務器加載配置屬性源
