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

Salesforce Apex:Trailhead单元测试中Test.setMock方法签名报错

Apex Rest Callouts单元测试方法签名错误排查

我正在学习Apex Rest Callouts的Trailhead教程,教程要求为示例类编写单元测试,所有代码均为教程提供,但其中一行代码报错,我没有Apex相关经验,对此感到困惑。

报错代码

@isTest
private class AnimalsCalloutsTest {
    @isTest static  void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result, 'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(), 'The status code is not 200.');
        // Verify content type   
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');  
        // Verify the array contains 3 items     
        Map<String, Object> results = (Map<String, Object>) 
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(), 'The array should only contain 3 items.');          
}   
}

错误信息

错误出现在第10行Test.setMock(HttpCalloutMock.class, mock);,提示:

Method does not exist or incorrect signature: void setMock(System.Type, System.StaticResourceCalloutMock) from the type Test

可能的解决方法

  • 调整变量类型声明:将StaticResourceCalloutMock mock = new StaticResourceCalloutMock();改为HttpCalloutMock mock = new StaticResourceCalloutMock();。因为Test.setMock的第二个参数要求是HttpCalloutMock类型的实例,虽然StaticResourceCalloutMock是其子类,但显式声明为父类类型可以避免类型推断问题,修正后的代码片段:
    // Create the mock response based on a static resource
    HttpCalloutMock mock = new StaticResourceCalloutMock();
    mock.setStaticResource('GetAnimalResource');
    mock.setStatusCode(200);
    mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
    // Associate the callout with a mock response
    Test.setMock(HttpCalloutMock.class, mock);
    
  • 检查Org版本兼容性:确认你的Salesforce Org版本支持StaticResourceCalloutMock类,这个类是较新的标准Mock类,旧版本可能未提供。
  • 排查类名冲突:检查是否存在自定义的StaticResourceCalloutMock类,与标准类重名导致类型混淆。
  • 验证接口实现:确认StaticResourceCalloutMock已正确实现HttpCalloutMock接口(标准类默认已实现,但如果有自定义修改需检查)。

内容的提问来源于stack exchange,提问作者Moritz Roessler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:07:42