Skip to content

Instantly share code, notes, and snippets.

@tarot
Last active October 26, 2015 02:41
Show Gist options
  • Save tarot/abe8fe878defd49ab9be to your computer and use it in GitHub Desktop.
Save tarot/abe8fe878defd49ab9be to your computer and use it in GitHub Desktop.
@IsTest
private class CalloutSampleTest {
public class CalloutMock implements HttpCallout.Service {
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'
);
}
HttpCallout.setMock(HttpCalloutMock.class, new CalloutMock());
Test.startTest();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://login.salesforce.com');
new HttpCallout().send(req);
Test.stopTest();
}
}
public class HttpCallout {
public interface Service {
HttpResponse respond(HttpRequest req);
}
public class ServiceImpl implements Service {
public HttpResponse respond(HttpRequest req) {
return new Http().send(req);
}
}
private static Service impl {
get {
return impl == null ? impl = new ServiceImpl() : impl;
}
set;
}
public HttpResponse send(HttpRequest req) {
return impl.respond(req);
}
@TestVisible
private static void setMock(Service mock) {
impl = mock;
}
@TestVisible
private static void setMock(Type dummy, Service mock) {
setMock(mock);
}
}
@IsTest
private class HttpCalloutTest {
public class Mock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
return new HttpResponse();
}
}
@IsTest
static void cover() {
HttpCallout.setMock(HttpCalloutMock.class, new HttpCallout.ServiceImpl());
Test.setMock(HttpCalloutMock.class, new Mock());
new HttpCallout().send(new HttpRequest());
}
}
@tarot
Copy link
Author

tarot commented Oct 26, 2015

new Http().sendnew HttpCallout().sendに, implements HttpCalloutMockimplements HttpCallout.Serviceにすれば動くようにしている。

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