ballerinaballerina-swan-lake

Is there a way for a mock Function to return different values in subsequent calls?


I want a similar behaviour as below. How can I do it in Ballerina?

 isolated function testFunc() returns string|error {
      // ...
      return str;
 }

    // mocking testFunc

    string val1 = testFunc(); // return value 1
    string val2 = testFunc(); // return value 2

Solution

  • you can use https://ballerina.io/learn/test-ballerina-code/mocking/#stub-with-multiple-values-to-return-sequentially-for-each-function-call functionality if you are using object mocking. But with function mocking, There is no support for multiple stubs. You can reset the return value for a function call before each call. You can utilize the call option and implement the custom logic within that function as well.

    main.bal

    function to mock

    public function intAdd(int a, int b) returns int {
        return (a + b);
    }
    

    test.bal

    import ballerina/test;
    
    @test:Mock {functionName: "intAdd"}
    test:MockFunction intAddMockFn = new ();
    
    @test:Config {}
    function testReturn() {
        // Stub to return the specified value when the `intAdd` is invoked.
        test:when(intAddMockFn).thenReturn(20);
       
        // Stub to return the specified value when the `intAdd` is invoked with the specified arguments.
        test:when(intAddMockFn).withArguments(0, 0).thenReturn(-1);
    }
    

    As shown in above example you can mock a function differently based on the arguments.