You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ballerina学习问题:无法Mock graphql:Client

Ballerina中Mock graphql:Client失效问题

近期学习Ballerina时,遇到测试中无法Mock graphql:Client的问题——执行测试时触发了真实HTTP请求,返回凭证错误的HttpError。

测试代码

@test:Config {
    dataProvider: testExecuteDataProvider
}
function testExecute(string query) returns error? {
    GraphQlClient|error graphqlClient = new;

    if graphqlClient is error {
        test:assertFail("Unexpected: GraphQlClient is error");
    }
    
    final graphql:Client mockedClient = test:mock(graphql:Client);
    record {|anydata...;|} res = {"username": "test"};
    test:prepare(mockedClient).when("execute").thenReturn(res);
    
    graphql:GenericResponseWithErrors|record {|anydata...;|}|json|graphql:ClientError result = check graphqlClient.execute(query = query);
    if result is graphql:GenericResponseWithErrors {
        test:assertFail("Unexpected: executed response is graphql:GenericResponseWithErrors");
    }
    if result is json {
        test:assertFail("Unexpected: executed response is json");
    }
    if result is graphql:ClientError {
        test:assertFail("Unexpected: executed response is graphql:ClientError");
    }

}

错误信息

[因Mock未生效导致的HttpError]
error {ballerina/test:0}ExecutionError ("error {ballerina/graphql:1}HttpError&{ballerina/graphql:1}RequestError&{ballerina/graphql:1}ClientError ("GraphQL客户端错误",body={"message":"无效凭证","documentation_url":"https://docs.github.com/graphql"})")

问题原因

你创建了真实的GraphQlClient实例并调用其execute方法,但mock的mockedClient完全没被用到,测试自然会触发真实请求,返回凭证错误。

解决方法

直接使用mock客户端替代真实实例,确保测试调用的是mock对象的方法。修改后的测试代码如下:

@test:Config {
    dataProvider: testExecuteDataProvider
}
function testExecute(string query) returns error? {
    // 直接创建mock客户端,无需真实实例
    final graphql:Client mockedClient = test:mock(graphql:Client);
    record {|anydata...;|} res = {"username": "test"};
    test:prepare(mockedClient).when("execute").thenReturn(res);
    
    // 调用mock客户端的execute方法
    graphql:GenericResponseWithErrors|record {|anydata...;|}|json|graphql:ClientError result = check mockedClient.execute(query = query);
    
    if result is graphql:GenericResponseWithErrors {
        test:assertFail("异常:执行返回结果为graphql:GenericResponseWithErrors");
    }
    if result is json {
        test:assertFail("异常:执行返回结果为json");
    }
    if result is graphql:ClientError {
        test:assertFail("异常:执行返回结果为graphql:ClientError");
    }
}

如果你的业务代码依赖graphql:Client,建议通过依赖注入的方式传入客户端实例,测试时传入mock对象,这样就能彻底隔离真实请求。

内容的提问来源于stack exchange,提问作者yuya morimoto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:03:33