模拟 nil 结果时测试失败

Test failure when mocking nil result

当尝试 运行 模拟 nil return 值的测试时,出现以下错误。 有什么想法吗?

function f1() returns string?|error {
    return f2();
}

function f2() returns string?|error {
    return "done";
}

// --tests
import ballerina/test;

@test:Mock {
    functionName: "f2"
}
test:MockFunction mockF2 = new;

@test:Config
function shouldReturnNil() {
    // arrange
    test:when(mockF2).thenReturn(());

    // act
    string?|error result = f1();

    // assert
    if result is error {
        test:assertFail(string `Expected nil, got error ${result.message()}`);
    } else if result is string {
        test:assertFail(string `Expected nil, got string ${result}`);
    }
}

Error:
Running Tests
        hello
                [fail] shouldReturnNil:
                    {ballerina}TypeCastError {"message":"incompatible types: 'error' cannot be cast to '(any|ballerina/test:0.8.0:Error)'"}
                        at ballerina.test.0_8_0:mockHandler(mock.bal:378)
                        ppp.hello.0_1_0:f1(main.bal:2)
                        ppp.hello.0_1_0.tests.main_test:shouldReturnNil(tests/main_test.bal:14)
0 passing
1 failing
0 skipped
test:when(mockF2).thenReturn(());

不适用于“()”值。如果你需要return一个nil值,你需要使用下面的方法。

test:when(mockF2).call("mockNilReturn");

您需要按如下方式定义 'mockNilReturn' 函数。

function mockNilReturn() returns string?|error {
    return ();
}