unit-testingmockingballerinaballerina-swan-lake

How to mock a function in a imported ballerina local module in unit test


I've created a ballerina module as below which is maintained in my local registry.

import wso2/notification_grpc_client as ngc;

In a seperate module, In a test case I am importing the other module and trying to mock the response in one of the methods in a class in the above imported module.

NotificationResponse noti = {code: "OK"};
ngc:NotificationServiceClientImpl clientMock = test:mock(ngc:NotificationServiceClientImpl);
test:prepare(clientMock).when("createApplication").thenReturn(noti);

but when test case is running it's getting executed without just returning mock response.


Solution

  • You can resolve this by adding a function to return the mock response with @test:Mock configurations.

    @test:Mock {functionName: "createApplication", moduleName: "wso2/notification_grpc_client"}
    public isolated function createApplicationMock(ApplicationGRPC createApplicationRequest, string endpoint) returns error|NotificationResponse {
        NotificationResponse noti = {code: "OK"};
        return noti;
    }