LoginSignup
1
0

More than 3 years have passed since last update.

Apex Specialist Super Badge 復習[Challenge 5]

Last updated at Posted at 2019-09-16

REST コールアウトのテスト

trailheadのとおり、Mockを作る
Apex REST コールアウト 単元 | Salesforce Trailhead

要件にHttpCalloutMockを使うとあるのでそのとおりにすればよいが、模擬データとなるJSONの作成が けっこう面倒くさい ので、リクエスト先のJSONデータを静的リソースとして保存して使うことにした。
ちなみに(このChallengeでは使えないが)静的リソースを使う場合はStaticResourceCalloutMockを使うこともできる。はず。

静的リソースの作成

File→new→Static Resourceと選択
MIME Type: text/plain

コールアウト先の情報を全部コピー&ペーストして保存。

データをStringとして取得するには

  1. StaticResourceオブジェクトとして取得
  2. Bodyを参照してStringに変換

StaticResourceオブジェクトにSOQLを使ってリソースの取得を行うことができる。

StaticResource sr=[SELECT id,Name,Body,ContentType
                   FROM StaticResource
                   WHERE Name='filename'
                   LIMIT 1];
//Name:ファイル名(拡張子なし)
//Body:本文
//ContentType:MIME/Type。今回はtext/plain

拡張子による区別もしたいならContentTypeを使えばできそう(未検証)

StaticResource.Bodyにファイル本文のデータが入っているのでStringに変換する。

参考

ソースコード

※静的リソースは省略

WarehouseCalloutServiceMock

コード
@isTest
global class WarehouseCalloutServiceMock implements HttpCalloutMock{
    // implement http mock callout
    global HTTPResponse respond(HTTPRequest request){
        HttpResponse response =new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        //saved 'warehouseJSON.txt' as static resource
        StaticResource staticResource=[SELECT Body
                                       FROM StaticResource
                                       WHERE Name='warehouseJSON' LIMIT 1];
        response.setBody(staticResource.Body.toString());
        response.setStatusCode(200);
        return response;
    }
}

WarehouseCalloutServiceTest

例のごとくassertする必要がないので、ひとまずCheck抜けるために作成。
assert要になった模様

コード
@isTest
private class WarehouseCalloutServiceTest {
  // implement your mock callout test here
    @isTest static void testWarehouseCalloutService(){
        Test.setMock(HttpCalloutMock.class,new WarehouseCalloutServiceMock());
        WarehouseCalloutService.runWarehouseEquipmentSync();
    }
}

続き:Apex Specialist Super Badge 復習[Challenge 6]

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0