I am unable to cover the below function in test class as siteId is always returned null

Id siteId = Site.getSiteId();
if (siteId != null) {
  //Community user logic -- THIS IS THE PART THAT IS NOT COVERED

} else {
  //Non-Community User Logic

I have tried including Test.isRunningTest() but then it causes a problem with the else block being covered...

I have checked the Site.createPortalUser documentation and also found similar question for the same : Known Question

These are very old threads and was wondering if there were any recents updates to solve this issue now.. Any known solutions or pointers that could help?

Thanks in advance.


Thanks to @Robert Sösemann, I believe you can apply Facade logic for all Platform methods.

You can just change the return type to String, because all Ids are string, but not all strings are ID in apex.

public with sharing class SiteFacade {

    private static String strSiteId = 'DummySiteId';

    public static String getSiteId(){
        return (Test.isRunningTest()) ? strSiteId : Site.getSiteId();


and your test will look like this:

static void runTest() {
    SiteFacade.strSiteId = 'DummyId';
    SiteFacade.strSiteId = null;

And your class like:

public static void testSiteLogic(){
    String siteId = SiteFacade.getSiteId();
    if (siteId != null) {
        System.debug('If- > '+siteId);

    } else {
        System.debug('Else -> '+siteId);

NOTE: Make sure to check if that Id value being used in code does not throw any System.StringException: Invalid id: DummyId.

  • thanks a lot man!! this solution worked like a charm and it is also re-usable in other components 🚀
    – Abhijith E
    Jan 12 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.