Salesforce调用接口APEX

1.调用

public class JHRest_CTIAudioTransforCls {
    public static List audioTransfor(String fileLink) {
        PostMessage postMessage = new PostMessage();
        // postMessage.fileLink = 'https://aliyun-nls.oss-cn-hangzhou.aliyuncs.com/asr/fileASR/examples/nls-sample-16k.wav';
        postMessage.fileLink = fileLink;
        System.debug(postMessage);
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('请求地址');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Content-Length', '0');
        req.setTimeout(120000);
        req.setBody(JSON.serialize(postMessage));
        System.debug('----》' + req.getEndpoint());
        HttpResponse res = h.send(req);
        System.debug('status---->' + res.getStatusCode());
        System.debug('body---->' + res.getBody());
        List results = (List) JSON.deserializeUntyped(res.getBody());
        System.debug('results--->'+results);
        return results;
    }


    public class PostMessage {
        public String fileLink;
    } 
  
}

 

测试类分为2个部分:

模拟resopnse部分:

@IsTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('请求地址', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        List responDatas=new List();
        ResponData respon=new ResponData();
        respon.EndTime='2350';
        respon.SilenceDuration=0;
        respon.BeginTime=340;
        respon.Text='北京的天气。';
        respon.ChannelId=0;
        respon.SpeechRate=149;
        respon.EmotionValue=5.1;
        responDatas.add(respon);
        String bodyText = JSON.serialize(responDatas);
        res.setBody(bodyText);
        res.setStatusCode(200);
        return res;
    }
    global class ResponData{
        global String EndTime;
        global Integer SilenceDuration;
        global Integer BeginTime;
        global String Text;
        global Integer ChannelId;
        global Integer SpeechRate;
        global Decimal EmotionValue;
    }
}

第二部分:调用的测试类:

@IsTest
global class JH_AudioTransForLogButton_Test{
    @IsTest
    static void testBehavior() {

        // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        insert interactionLog;
        Test.startTest();
        List res = JHRest_CTIAudioTransforCls.audioTransfor('参数'); 
        Test.stopTest();
    }

} 
  

 

注意的是在设置mock的时候body设置要确保跟请求的返回值一致,不然会出现格式错误等问题

你可能感兴趣的:(salesforce,接口,json)