Skip to content

Instantly share code, notes, and snippets.

@tarot
Last active August 21, 2020 02:10
Show Gist options
  • Save tarot/43430fd7192d9dffd248 to your computer and use it in GitHub Desktop.
Save tarot/43430fd7192d9dffd248 to your computer and use it in GitHub Desktop.
@IsTest
private class CalloutSampleTest {
public class CalloutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
return new HttpResponse();
}
}
@IsTest
static void test() {
System.runAs([select Id from User where Id = :UserInfo.getUserId()][0]) {
String name = EncodingUtil.convertToHex(Crypto.generateAesKey(128));
insert new User(
LastName = name,
Username = name + '@example.com',
Email = name + '@example.com',
ProfileId = UserInfo.getProfileId(),
Alias = name.left(8),
TimeZoneSidKey = 'Asia/Tokyo',
LocaleSidKey = 'ja_JP',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'ja'
);
}
Test.startTest();
Test.setMock(HttpCalloutMock.class, new CalloutMock());
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://login.salesforce.com');
new Http().send(req);
Test.stopTest();
}
}
@tarot
Copy link
Author

tarot commented Oct 26, 2015

何故かcs5でこうなる。ap2ではならない。

Class.CalloutSampleTest.test: line 34, column 1
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

@tarot
Copy link
Author

tarot commented Oct 26, 2015

insertするのがUserじゃない場合は(少なくともAccount, Contact, カスタムオブジェクトでは)ならない。
insertしなくてももちろんならない。

ちなみにTest.setMockしない時の例外メッセージはこれ

TestMethod として定義されたメソッドは、Web サービスコールアウトをサポートしないため、テストはスキップされます。

@tarot
Copy link
Author

tarot commented Oct 26, 2015

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_dml.htm

The Test.startTest statement must appear before the Test.setMock statement.

と書いてあるけど順番が逆でも挙動は変わらない様子。

@tarot
Copy link
Author

tarot commented Oct 29, 2015

コミュニティを有効化していた時に発生するバグだったらしい。cs5が悪いのではなかった。

@tarot
Copy link
Author

tarot commented Oct 30, 2015

修正されました

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment