3

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
ThisaruG
  • 3,222
  • 7
  • 38
  • 60
Bondowe
  • 75
  • 4

1 Answers1

1
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 ();
}
ThisaruG
  • 3,222
  • 7
  • 38
  • 60
Fathima
  • 85
  • 1
  • 1
  • 9