Newer Version Available
Testing ConnectApi Code
Connect in Apex methods don’t run in system mode, they run in the context of the current user (also called the context user). The methods have access to whatever the context user has access to. Connect in Apex doesn’t support the runAs system method.
Most Connect in Apex methods require access to real org data, and fail unless used in test methods marked @IsTest(SeeAllData=true).
However, some Connect in Apex methods, such as getFeedElementsFromFeed, are not permitted to access org data in tests and must be used with special test methods that register outputs to be returned in a test context. If a method requires a setTest method, the requirement is stated in the method’s “Usage” section.
A test method name is the regular method name with a setTest prefix. The test method signature (combination of parameters) matches a signature of the regular method. For example, if the regular method has three overloads, the test method has three overloads.
Using Connect in Apex test methods is similar to testing web services in Apex. First, build the data you expect the method to return. To build data, create output objects and set their properties. To create objects, you can use no-argument constructors for any non-abstract output classes. If you’re testing binary input parameters, use the same instance for creating and executing data.
After you build the data, call the test method to register the data. Call the test method that has the same signature as the regular method you’re testing.
After you register the test data, run the regular method. When you run the regular method, the registered data is returned.
1global class NewsFeedClass {
2 global static Integer getNewsFeedCount() {
3 ConnectApi.FeedElementPage elements =
4 ConnectApi.ChatterFeeds.getFeedElementsFromFeed(null,
5 ConnectApi.FeedType.News, 'me');
6 return elements.elements.size();
7 }
8}1@isTest
2private class NewsFeedClassTest {
3 @IsTest
4 static void doTest() {
5 // Build a simple feed item
6 ConnectApi.FeedElementPage testPage = new ConnectApi.FeedElementPage();
7 List<ConnectApi.FeedItem> testItemList = new List<ConnectApi.FeedItem>();
8 testItemList.add(new ConnectApi.FeedItem());
9 testItemList.add(new ConnectApi.FeedItem());
10 testPage.elements = testItemList;
11
12 // Set the test data
13 ConnectApi.ChatterFeeds.setTestGetFeedElementsFromFeed(null,
14 ConnectApi.FeedType.News, 'me', testPage);
15
16 // The method returns the test page, which we know has two items in it.
17 Test.startTest();
18 System.assertEquals(2, NewsFeedClass.getNewsFeedCount());
19 Test.stopTest();
20 }
21}