Find your content:

Search form

You are here

test method always fails. why isn't the soql returning any records?

 
Share

I've been running a chatter tutorial and ran across something I don't understand.

First off here's the link to the tutorial .

The following code is straight out of the tutorial and works, except for the test method. The test method fails on the first assert() every time. The reason it fails is because the array is always empty.

Why is the test method failing but the visualforce page works fine? Better yet, why isn't the getRecentTextUpdates() returning anything in the test method?

<apex:page controller="NewsFeedController" sidebar="false">
  <h1>News Feed</h1>
  <apex:form >
      <apex:inputText value="{!feedUpdate}"/>
      <apex:commandButton value="Update" action="{!go}" reRender="recent"/>

      <apex:outputPanel id="recent">
          <apex:dataList value="{!recentTextUpdates}" var="update">
              <apex:outputText value="{!update.body}"></apex:outputText>
          </apex:dataList>
      </apex:outputPanel>
  </apex:form>
</apex:page> 

public class NewsFeedController {

    @isTest
    static void testUpdates() {
        NewsFeedController con = new NewsFeedController();
        con.feedUpdate = 'Hi';
        con.go();
        List<NewsFeed> newsFeed = con.getRecentTextUpdates();
        System.debug('My NewsFeed Size: ' + newsFeed.size());
        System.assert(newsFeed.size() > 0);
        System.assertEquals('Hi', newsFeed[0].Body);
    }

    public PageReference go() {
        FeedItem feedItem = new FeedItem();
        feedItem.Type = 'TextPost';
        feedItem.ParentId = UserInfo.getUserId();
        feedItem.Body = this.feedUpdate;
        insert feedItem;

        return null;
    }

    public List<NewsFeed> getRecentTextUpdates() {
        List<NewsFeed> newsFeed = [SELECT Type, CreatedDate, CreatedBy.Name, Body FROM NewsFeed WHERE Type = 'TextPost' ORDER BY CreatedDate DESC LIMIT 10];

        return newsFeed;
    }


    public String feedUpdate { get; set; }
}

Attribution to: fourq

Possible Suggestion/Solution #1

You might need to check API version, I faced similar issue in API v24 update. I have to lower down API version 23 to get rid of it. More details in this blog post here : http://www.tgerm.com/2012/04/chatter-apex-test-case-bug-in-api.html


Attribution to: Abhinav Gupta

Possible Suggestion/Solution #2

From API version 24, Salesforce stop supporting real records in test cases. To access the real records, add the tag (SeeAllData=true) in your test class,

@isTest(SeeAllData=true)
public class TestCase{
  static testMethod void TestMethodOne() { 
  }
}

Attribution to: Muzaffer
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3795

My Block Status

My Block Content