Search code examples
corda

How to unit-test `Contract` whose state contains `StatePointer`


When I test the a Contract whose ContractState has a LinearPointer to another state, the log first shows the warning

[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.

and of course the test failed, because the LedgerTransaction verified by the Contract do not have the pointed-to state resolved.

So I followed the instruction and passed the MockService to the TransactionBuilder. But the following error occured:

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)

When I dug into the source code, I found that MockService's vaultService can not be retrieved:

override val vaultService: VaultService get() = throw UnsupportedOperationException()

So, how am I supposed to test this kind of Contract whose verification involves resolving states referenced by StatePointers?


Solution

  • Ok, a solution struck me when I am writing the question:

    Mannually add the pointed-to state to the transaction as a reference state