Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Cannot mock http:Client by creating test double #41821

Closed
niveathika opened this issue Dec 4, 2023 · 6 comments
Closed

[Bug]: Cannot mock http:Client by creating test double #41821

niveathika opened this issue Dec 4, 2023 · 6 comments
Labels
Area/TestFramework Reason/Invalid Issue is invalid. Team/DevTools Ballerina Developer Tooling ( CLI, Test FW, Package Management, OpenAPI, APIDocs ) Type/Bug

Comments

@niveathika
Copy link
Contributor

niveathika commented Dec 4, 2023

Description

The code given in https://ballerina.io/learn/test-ballerina-code/mocking/#create-a-test-double is not working.

remote isolated function get(string path, map<string|string[]>? headers = (),
            http:TargetType targetType = http:Response) returns http:Response  |http:ClientError {

The above results in

error: incompatible return type provided for function 'get()'
        at ballerina.test.0:mock(mock.bal:309)
           ballerinax.googleapis.gmail.oas$test.4.tests.test:getMockClient(tests/test.bal:29)
           ballerinax.googleapis.gmail.oas.4.Client:init(client.bal:43)
remote isolated function get(string path, map<string|string[]>? headers = (),
            http:TargetType targetType = http:Response) returns http:Response | anydata |http:ClientError {

This results in following error,

error("{ballerina}TypeCastError",message="incompatible types: 'http:Response' cannot be cast to 'error'")
                                callableName: $get$users$^$profile moduleName: ballerinax.googleapis.gmail.oas.4.Client fileName: client.bal lineNumber: 700
                                callableName: testGmailGetProfile moduleName: ballerinax.googleapis.gmail.oas$test.4.tests.test fileName: tests/test.bal lineNumber: 34
                                callableName: testGmailGetProfile$lambda0$ moduleName: ballerinax.googleapis.gmail.oas$test.4.tests.test_execute-generated_1 fileName: tests/test_execute-generated_1.bal lineNumber: 4

Steps to Reproduce

No response

Affected Version(s)

No response

OS, DB, other environment details and versions

No response

Related area

-> Test Framework

Related issue(s) (optional)

No response

Suggested label(s) (optional)

No response

Suggested assignee(s) (optional)

No response

@ballerina-bot ballerina-bot added Team/DevTools Ballerina Developer Tooling ( CLI, Test FW, Package Management, OpenAPI, APIDocs ) Area/TestFramework labels Dec 4, 2023
@Dilhasha
Copy link
Contributor

Dilhasha commented Dec 4, 2023

I was able to reproduce the mentioned error with the following example.

main.bal

import ballerina/http;
import ballerina/regex;

http:Client clientEndpoint = check new ("https://api.chucknorris.io/jokes/");

type Joke readonly & record {|
string value;
|};

// This function performs a `get` request to the Chuck Norris API and returns a random joke
// with the name replaced by the provided name or an error if the API invocation fails.
function getRandomJoke(string name) returns string|error {
Joke joke = check clientEndpoint->get("/random");
string replacedText = regex:replaceAll(joke.value, "Chuck Norris", name);
return replacedText;
}

main_test.bal

import ballerina/test;
import ballerina/http;

// An instance of this object can be used as the test double for the `clientEndpoint`.
public client class MockHttpClient {

remote function get(string path, map<string|string[]>? headers = (), http:TargetType targetType = http:Response) returns http:Response|anydata|http:ClientError {
// Joke joke = {"value": "Mock When Chuck Norris wants an egg, he cracks open a chicken."};
return {"value": "Mock When Chuck Norris wants an egg, he cracks open a chicken."};
}

}

@test:Config {}
public function testGetRandomJoke() {

// create and assign a test double to the `clientEndpoint` object
clientEndpoint = test:mock(http:Client, new MockHttpClient());

// invoke the function to test
string|error result = getRandomJoke("Sheldon");

// verify that the function returns the mock value after replacing the name
test:assertEquals(result, "Mock When Sheldon wants an egg, he cracks open a chicken.");
}

@Dilhasha
Copy link
Contributor

Dilhasha commented Dec 4, 2023

The issue occurs when you try to return the record directly as follows.
return {"value": "Mock When Chuck Norris wants an egg, he cracks open a chicken."};

But if you assign it to a variable and return, this error can be avoided.

Joke joke = {"value": "Mock When Chuck Norris wants an egg, he cracks open a chicken."};
return joke;

@niveathika Until we fix the issue can you use it as a workaround?

@niveathika
Copy link
Contributor Author

niveathika commented Dec 4, 2023

Ack. I will use this workaround for the time being

@gayaldassanayake
Copy link
Contributor

Faced a similar issue when mocking an http:Client with a post(). Assigning and returning worked fine, but we might at least need to document this.

@Dilhasha
Copy link
Contributor

Closing this since a workaround is provided.

Copy link

This issue is NOT closed with a proper Reason/ label. Make sure to add proper reason label before closing. Please add or leave a comment with the proper reason label now.

      - Reason/EngineeringMistake - The issue occurred due to a mistake made in the past.
      - Reason/Regression - The issue has introduced a regression.
      - Reason/MultipleComponentInteraction - Issue occured due to interactions in multiple components.
      - Reason/Complex - Issue occurred due to complex scenario.
      - Reason/Invalid - Issue is invalid.
      - Reason/Other - None of the above cases.

@Dilhasha Dilhasha added the Reason/Invalid Issue is invalid. label Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area/TestFramework Reason/Invalid Issue is invalid. Team/DevTools Ballerina Developer Tooling ( CLI, Test FW, Package Management, OpenAPI, APIDocs ) Type/Bug
Projects
None yet
Development

No branches or pull requests

4 participants