I have a package like the following:
FooClient ep;
function init() returns error? {
do {
ep = check new ("https://some-api", "id", "secret");
// do some more stuff
} on fail var e {
// log error
return e;
}
}
function funcToBeTested() returns anydata {
return "foo";
}
When initialising the FooClient
instance, it'll make a network call to retrieve a token to be used by the client. I also have functions such as funcToBeTested
which are modular pieces of logic that I want to test by writing unit tests. However running these unit tests is an issue because when the tests run, the module init function runs too. Which means I have to provide proper credentials for some-api even when running the unit tests. But I don't want to do that since the functionalities I do want to test have no relation to that client initialisation. Is there a way around this?
We can make use of function mocking to get around this.
We can introduce a function to initialise the fooClient
and then mock that function using function mocking to return a mock client instead of the original client.
You can refer to the test guide at https://ballerina.io/learn/test-ballerina-code/test-services-and-clients/#mock-final-clients for further details.