首页 > 其他分享 >【salesforce技术积累】-REST CALLOUT处理

【salesforce技术积累】-REST CALLOUT处理

时间:2023-06-21 17:02:18浏览次数:44  
标签:salesforce animals CALLOUT request System REST HttpResponse response mock

1.HTTP 和 callout基本

・Rest CallOut 是基于HTTP的,一般的HTTP函数有以下几种。

  ①:GET ➡ 用于获取指定数据

  ②:POST ➡ 用于做成数据

  ③:DELETE ➡ 用于删除数据

  ④:PUT ➡ 用于更新数据

 

 2.具体事例

・リモートサイト的设定

 代码演示:

public class AnimalsCallouts {
    public static HttpResponse makeGetCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        // If the request is successful, parse the JSON response.
        if(response.getStatusCode() == 200) {
            // Deserializes the JSON string into collections of primitive data types.
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'animals' key as a list
            List<Object> animals = (List<Object>) results.get('animals');
            System.debug('Received the following animals:');
            for(Object animal: animals) {
                System.debug(animal);
            }
        }
        return response;
    }
    public static HttpResponse makePostCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody('{"name":"mighty moose"}');
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if(response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
        return response;
    }        
}

对于CALLOUT的测试,需要使用模拟送信,有2种,一种是使用静态代码(StaticResourceCalloutMock),一种是使用HttpCalloutMock。

・StaticResourceCalloutMock的测试代码

①:需要先设定静态源码(假设被测试的代码正方终了后该有的结果)

②:测试代码

@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.');          
    }   
}

・HttpCalloutMock的测试代码

需要实现HttpCalloutMock接口,重写里面的respond函数。

@isTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
}

下面是具体的测试

@isTest 
static void testPostCallout() {
    // Set mock callout class 
    Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock()); 
    // This causes a fake response to be sent
    // from the class that implements HttpCalloutMock. 
    HttpResponse response = AnimalsCallouts.makePostCallout();
    // Verify that the response received contains fake values
    String contentType = response.getHeader('Content-Type');
    System.assert(contentType == 'application/json');
    String actualValue = response.getBody();
    System.debug(response.getBody());
    String expectedValue = '{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}';
    System.assertEquals(expectedValue, actualValue);
    System.assertEquals(200, response.getStatusCode());
}

标签:salesforce,animals,CALLOUT,request,System,REST,HttpResponse,response,mock
From: https://www.cnblogs.com/zhylibrary/p/17496678.html

相关文章

  • net 中的 new RestRequest()代码举开发过程中实用的例子
    //创建一个RestClient对象varclient=newRestClient("http://api.openweathermap.org");//创建一个RestRequest对象varrequest=newRestRequest("/data/2.5/weather",Method.GET);//添加请求参数request.AddParameter("q","London");......
  • 使用presto 进行跨库数据对比
     明细+汇总 1SELECT2concat(3'selecta.*from('4,concat('',array_join(TRANSFORM(table_catalog_schema,_->concat('selectid,map(array[',column_name_str,'],split(',array_join(TRANSFORM(column_nam......
  • java+rest方式写一个邮件发送接口
     1<!--发邮件-->2<dependency>3<groupId>org.springframework.boot</groupId>4<artifactId>spring-boot-starter-mail</artifactId>5</dependency>67<dep......
  • 微服务 – Spring Cloud – Eureka - RestTemplate和@LoadBalanced 实现服务发现调用(
    背景:服务注册用的是Eureka集群。服务调用用的是注解@LoadBalanced和RestTemplate服务数量两个:order服务和pyment服务(order服务是调用者。payment服务是被调用者)首先将order服务和payment服务注册Eureka集群中。通过order调用payment服务Eureka集......
  • django+pip install djangorestframework
    ###################### pipinstalldjangopipinstalldjangorestframeworkdjango-adminstartprojectexample.pyuthonmanage.pymigratepythonmanage.pycreatesuperuser                 ##################### ......
  • 8. RESTful案例
    1.准备工作‍和传统CRUD一样,实现对员工信息的增删改查。搭建环境准备实体类packagecom.atguigu.mvc.bean;publicclassEmployee{  privateIntegerid;  privateStringlastName;  privateStringemail;  //1male,0female  privateI......
  • 使用graylog rest api查询日志
    由于项目需要,调研使用graylog收集项目操作日志,并使用api查询日志python代码if__name__=='__main__':importrequestssearch_content={"query_string":{"type":"elasticsearch","query_string&q......
  • 7. RESTful
    1.RESTful简介‍REST:RepresentationalStateTransfer,表现层资源状态转移。①资源‍资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、......
  • 泛微eteams+RestCloud,实现企业数据的高效获取与同步
    泛微eteams是一种企业级团队协作软件,类似于微软Teams、Slack等工具。它提供了实时聊天、视频会议、文件共享、任务管理、日程安排等功能,旨在提高团队协作和沟通效率。泛微eteams还与泛微OA、泛微移动审批等企业应用进行了集成,可以实现跨系统的数据传递和协同工作。企业往往会有将......
  • 【salesforce技术积累】-APEX调用外部服务概念理解(包含外部站点设置)
    1.基本概念・salesforce中的「コールアウト」指的是salesforce作为客户端去调用其他的服务,「Webサービス」指的是salesforce作为服务器被其他客户端调用。(个人理解)下面这个网站是其他人的解释说明:Salesforce(他システムとの連携メモ)-Qiita打不开的小伙伴请继续看下面。。。......