I'm currently writing unit tests for the functions inside the "ConsentManagementServiceImpl" class.However, the initiation of this class involves creating a DAO layer object. I want to mock the private final object (consentManagementDAO) and mock its methods whenever they are called. How can I do that?
Here is my code
public isolated client class ConsentManagementImpl {
private final dao:ConsentManagementDAO consentManagementDAO;
public isolated function init(string host, string username, string password, string database, int port) returns error? {
self.consentManagementDAO = check new(host, username, password, database, port);
}
public isolated function handle consentAmendment(string consenId, string payload, string orgId) returns error?
check self.consentManagementDAO->updateConsent(consentId, orgId, payload);
}
}
Since consentManagementDAO
is within the scope of the client class ConsentManagementServiceImpl
, we cannot mock it as it is. With the current implementation, we can only mock the ConsentManagementServiceImpl
using object mocking. But, that way we can't test the implementation within that class.
To achieve the requirement, we can move the consentManagementDAO
out of the class(as a module level final client) and then use the approach mentioned in https://ballerina.io/learn/test-ballerina-code/test-services-and-clients/#mock-final-clients to mock this final client.