Is it possible to test the "else" part of my apex method?

Here is the code of my method:

@AuraEnabled(cacheable=true)
public static String getCity() {
    User currentUser = [SELECT City FROM User WHERE Id = :UserInfo.getUserId() AND City != ''];
    if(currentUser.City != ''){
        return currentUser.City;
    } else {
        Default_city__mdt defaultCity = [SELECT City__c FROM Default_city__mdt Limit 1];
        return defaultCity.City__c;
    }    
}

And this is the code of my test method, which covers only part of the method:

@isTest static void testGetCityCurrentUser(){
    String city = WebServiceLWC.getCity();
    System.assertNotEquals(null, city, 'city value is null');
}

How do I cover the rest of my method? After all, the value of 'City' always remains filled in and I will not get into the else part of the method in any way…

here is solutions:

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Solution 1

Your code can throw a "No rows returned" QueryException, because you’re filtering to see if the city is not blank/null. Instead, consider code like this:

@AuraEnabled(cacheable=true)
public static String getCity() {
    for(User currentUser: [SELECT City FROM User WHERE Id = :UserInfo.getUserId() AND City != null]) {
        return currentUser.City;
    }
    return [SELECT City__c FROM Default_city__mdt Limit 1].City__c;
}

Now, in order to test both paths, update your city:

@isTest static void testGetCityCurrentUser(){
    update new User(Id=UserInfo.getUserId(),City='Somewhere');
    String city = WebServiceLWC.getCity();
    System.assertNotEquals(null, city, 'city should not be null');
    update new User(Id=UserInfo.getUserId(),City=null);
    city = WebServiceLWC.getCity();
    System.assertEquals(null, city, 'city should be null');
}

Note that I set City to ensure that it is not null before attempting to call your test. This prevents "random" failures depending on who runs the code.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply