如何对状态包含 StatePointer 的 `Contract` 进行单元测试
How to unit-test `Contract` whose state contains `StatePointer`
当我测试 Contract
的 ContractState
有一个 LinearPointer
到另一个状态时,日志首先显示警告
[WARN] 15:13:20,131 [Test worker] transactions.TransactionBuilder. - WARNING: You must pass in a ServiceHub reference to TransactionBuilder to resolve state pointers outside of flows. If you are writing a unit test then pass in a MockServices instance.
当然测试失败了,因为 Contract
验证的 LedgerTransaction
没有解决指向的状态。
所以我按照说明将 MockService
传递给了 TransactionBuilder
。但是出现如下错误:
java.lang.UnsupportedOperationException
at net.corda.testing.node.MockServices.getVaultService(MockServices.kt:438)
at net.corda.core.contracts.LinearPointer.resolve(StatePointer.kt:183)
at net.corda.core.transactions.TransactionBuilder.resolveStatePointers(TransactionBuilder.kt:738)
at net.corda.core.transactions.TransactionBuilder.addOutputState(TransactionBuilder.kt:804)
挖源码的时候,发现MockService
的vaultService
找不回来了:
override val vaultService: VaultService get() = throw UnsupportedOperationException()
那么,我应该如何测试这种 Contract
,其验证涉及解析 StatePointer
s 引用的状态?
好的,当我写这个问题时,一个解决方案让我印象深刻:
手动将指向的状态添加到事务中作为参考状态
当我测试 Contract
的 ContractState
有一个 LinearPointer
到另一个状态时,日志首先显示警告
[WARN] 15:13:20,131 [Test worker] transactions.TransactionBuilder. - WARNING: You must pass in a ServiceHub reference to TransactionBuilder to resolve state pointers outside of flows. If you are writing a unit test then pass in a MockServices instance.
当然测试失败了,因为 Contract
验证的 LedgerTransaction
没有解决指向的状态。
所以我按照说明将 MockService
传递给了 TransactionBuilder
。但是出现如下错误:
java.lang.UnsupportedOperationException
at net.corda.testing.node.MockServices.getVaultService(MockServices.kt:438)
at net.corda.core.contracts.LinearPointer.resolve(StatePointer.kt:183)
at net.corda.core.transactions.TransactionBuilder.resolveStatePointers(TransactionBuilder.kt:738)
at net.corda.core.transactions.TransactionBuilder.addOutputState(TransactionBuilder.kt:804)
挖源码的时候,发现MockService
的vaultService
找不回来了:
override val vaultService: VaultService get() = throw UnsupportedOperationException()
那么,我应该如何测试这种 Contract
,其验证涉及解析 StatePointer
s 引用的状态?
好的,当我写这个问题时,一个解决方案让我印象深刻:
手动将指向的状态添加到事务中作为参考状态