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
Spencer BerkSpencer Berk 

How do I add a test class to my Apex class to increase code coverage?

How do I add a test class in this Apex class to increase my code coverage? When I try and deploy this apex class, I recieve a "Code Coverage error" with only 74% coverage.
public class NapiliCommunityController2 {
    @AuraEnabled
    public static User getLoggedInUser(){
        return [SELECT Id, Contact.AccountId FROM User WHERE Id =: UserInfo.getUserId() LIMIT 1];
    }
}

 
Best Answer chosen by Spencer Berk
SwethaSwetha (Salesforce Developers) 
HI Spencer,
Please see https://salesforce.stackexchange.com/questions/245838/how-to-test-the-current-logged-in-user-in-test-class/245850 that explains writing test class for your scenario.

Unit tests have a running user, too, just like any Apex code. If you were to write a unit test that called this method,your code should be like
@isTest
public class napilicommunityTestclass {
@isTest
public static void does_query_current_user() {
    System.assertEquals(UserInfo.getUserId(), NapiliCommunityController2.getLoggedInUser().Id, 'got the right user');
}
}

and then go into your IDE or Developer Console and ask to run the test, you would be the running user. UserInfo.getUserId() would return your user Id, and the query would find your user record.
User-added image

In some situations, you'll be testing code that is dependent on who the running user is (this code is not). In those situations, your unit test will often need to create and insert its own User record that has the correct role and profile, and then invoke the code that's being tested within a System.runAs() block:
User myTestUser = UserFactory.createTestUser();
System.runAs(myTestUser) {
    System.assertEquals(UserInfo.getUserId(), myClass.getUserInformation().Id, 'got the right user');
}
Then, the running user inside the runAs block will be myTestUser, and that user's Id will be returned for UserInfo.getUserId().

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you