Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test failure when mocking nil result

Tags:

ballerina

When trying to run a test that mocks a nil return value, I'm getting the following error. Any idea?

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
like image 888
Bondowe Avatar asked Mar 26 '26 09:03

Bondowe


1 Answers

test:when(mockF2).thenReturn(());

doesn't work with '()' values. If you need to return a nil value, you need to use the following approach.

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

You need to have 'mockNilReturn' function defined as follows.

function mockNilReturn() returns string?|error {
    return ();
}
like image 117
Fathima Avatar answered Mar 28 '26 02:03

Fathima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!