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
Sarah Maze 18Sarah Maze 18 

Test Class using AuthSession

I need to log the IP address of community users when they fill out a specific form on our community site (for legal reasons pertaining to financing). I am accomplishing this in the code using the following snippet:

Id customerId = UserInfo.getUserId();
AuthSession sess = [SELECT Id, SourceIp FROM AuthSession WHERE UsersId = :customerId     ORDER BY CreatedDate DESC LIMIT 1];
string ip = sess.SourceIp;

This runs fine, but when I run my test class, it says the query returns no rows. Is AuthSession not accessible to test classes? Is there a workaround?

Thank you.
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sarah,

Yes AuthSession is a readonly object. You cannot insert the data to it. Please find the below article for the same.

http://​​​​​​​https://salesforce.stackexchange.com/questions/139884/how-do-i-write-unit-test-against-the-authsession-object (http://https://salesforce.stackexchange.com/questions/139884/how-do-i-write-unit-test-against-the-authsession-object)


If this solution helps, Please mark it as best answer.

Thanks,
​​​​​​​
Sarah Maze 18Sarah Maze 18
Sai,

That link goes to an error. Do you have another link?

Other than simply skipping the code section with "if (!Test.isRunningTest())" is there another solution? I have to have the user's IP address, but if I use AuthSession in my code, I cannot have a test class unless I cheat and bypass it. That doesn't feel right to me.

Thanks.

Sarah