function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MichaelRusso212MichaelRusso212 

SessionID changes in test method

Hi,

 

I am trying to write a unit test for a method that inserts a record that uses the sessionId as part of the key. The sessionID is retrieved using UserInfo.getSessionId(). In my test, I invoke the method on my object that makes the insert, and then I try to retrieve that row using UserInfo.getSessionID(). However, the sessionID that is inserted from within my class is different than the one I see in my testmethod.

 

Here is the method I am trying to test: 

 

public void rateDocument() { docRating__c dr=new docRating__c (Rating__c=this.documentRating, DocumentID__c=this.documentID, Comments__c=this.documentFeedback,Rating_Session__c= UserInfo.getSessionId(),RatedBy__c=UserInfo.getUserId() ); insert dr; }

 

and here is my testmethod:

 

public static testmethod void testRateDocument() { User usr = [Select id,name,contactid from User where isActive = true and user.contact.id != null limit 1]; System.runAs(usr) { myController con = new myController(); con.documentRating=5; con.documentID='testdoc.html'; con.documentFeedback='awesomest doc ever'; con.rateDocument(); docRating__c docRating = [SELECT Rating__c,DocumentID__c, Comments__c, RatedBy__c FROM docRating__c WHERE Rating_Session__c=:UserInfo.getSessionId() AND RatedBy__c=:UserInfo.getUserId()]; System.assertEquals(docRating.Rating__c,con.documentRating); System.assertEquals(docRating.DocumentID__c, con.documentID); System.assertEquals(docRating.Comments__c, con.documentFeedback); } }

 

 

 

 

 When I run the testmethod like so, the testRunner complains that there are no rows being returned by my query into docRating__c. 

 

The way around this problem is to make the sessionId part of the class, and then use that sessionID when doing the query prior to the assertion. This is bad, however, because I don't want to have to add the sessionID to my controller and because the architecture shouldn't change to suit the tests. 

 

Does anyone know why this is happening? I thought that the sessionID might be changing as a result of the call to System.runAs(), but it doesn't. I looked at the UserInfo object before and after System.runAs, the name and userID will change accordingly, but sessionID stays the same. Regardless, the class method is being invoked from within the runAs block so that should be(?) using the UserInfo data as the testMethod.

 

Thanks,

 

Michael