首页 > 解决方案 > 是否可以在 Corda 的合同测试中以编程方式在分类帐内创建多个交易?

问题描述

是否可以在 Corda 的合同测试中以编程方式在分类帐内创建多个交易?当我删除 forEach 循环并复制并粘贴每个事务的代码(更改输出状态以匹配我想要测试的内容)时,一切都按预期工作。但是,如果我尝试重构它并像代码示例中那样在 forEach 循环中以编程方式生成事务,我的测试将失败。

@Test
fun simpleTest() {
    ledger {
        listOf(...).forEach { 
            transaction {
                command(participants, Commands.Command())
                input(Contract.ID, inputState)
                output(Contract.ID, outputState)
                failsWith("message")
            }
        }
    }
}

标签: kotlincorda

解决方案


回应您对我的评论的回复;我认为你应该尝试使用tweak.
在下面的示例中,您将看到我的事务如何具有相同的命令和输出,但我可以对其进行调整并尝试不同的输入:

@Test
@DisplayName("Testing different inputs.")
public void testDifferentInputs() {
    CustomState goodInput = new CustomState();
    CustomState badInput1 = new CustomState();
    CustomState badInput2 = new CustomState();
    CustomState output = new CustomState();

    ledger(ledgerServices, l -> {
        l.transaction(tx -> {
            // Same output and command.
            tx.output("mypackage.CustomState", output);
            tx.command(Collections.singletonList(myNode.getPublicKey()), new CustomStateContract.Commands.Create());
            // Tweak allows to tweak the transaction, in this case we're using bad input #1 and the transaction should fail.
            tx.tweak(tw -> {
                tw.input("mypackage.CustomState", badInput1);               
                return tw.failsWith("Bad Input State.");
            });
            // Tweak allows to tweak the transaction, in this case we're using bad input #2 and the transaction should fail.
            tx.tweak(tw -> {
                tw.input("mypackage.CustomState", badInput2);               
                return tw.failsWith("Bad Input State.");
            });
            // After the tweak we are using the good input and the transaction should pass.
            tx.input("mypackage.CustomState", goodInput);           
            return tx.verifies();
        });
        return Unit.INSTANCE;
    });
}

更多示例:https ://docs.corda.net/tutorial-test-dsl.html


推荐阅读