-1

I have below UserPackageLicense class and test class.I am unable to cover the test class try catch block Class:-

public class AssignPackageLicense {
public static boolean flag=true;
static String PACKAGE_NAMESPACE_PREFIX = System.Label.PACKAGE_NAMESPACE_PREFIX;
public static String exceptionText {get; set;}

public AssignPackageLicense() {
    exceptionText = 'Initialized';
}

static List<User> getUsersWithProfile(list<user> usr) {
    List<User> matchingUsers = new List<User>();
    list <id>userIds=new list<id>();      
    for(user u:usr) {
        userIds.add(u.id);
    }      
    matchingUsers = [SELECT Id FROM User where id in:userIds ];
    return matchingUsers;
}

public static void assignLicenseByProfile(List<user> usr) {
    //find the PackageLicense Id
    List<PackageLicense> pl = new list<PackageLicense>();
    pl=[SELECT Id, NamespacePrefix, AllowedLicenses, UsedLicenses, 
        ExpirationDate,Status FROM PackageLicense WHERE 
        NamespacePrefix = :PACKAGE_NAMESPACE_PREFIX];
    System.debug('pl>>>'+pl);
    if(pl.size()>0){
        System.assert(pl != null, 'PackageLicense cannot be null.');
        List<User> usersToAssignLicenses = getUsersWithProfile(usr);
        List<UserPackageLicense> firstUPLs = new List<UserPackageLicense>();

        //create a new UserPackageLicense record for each user with the specified profile
        for (Integer i = 0; i< usersToAssignLicenses.size(); i++){
            UserPackageLicense upl = new UserPackageLicense();
            upl.PackageLicenseId = pl[0].Id;
            upl.UserId = usersToAssignLicenses[i].Id;
            firstUPLs.add(upl);
        }
        System.debug('firstUPLs>>>'+firstUPLs);
        try {
            //bulk insert
            insert(firstUPLs);
        } catch(DmlException e) {
            for (Integer i = 0; i < e.getNumDml(); i++) {
                // process exception here 
                System.debug(e.getDmlMessage(i)); 
                String status = e.getDmlStatusCode(i);
                System.debug(status + ' ' + e.getDmlMessage(i));
                if(status.equals('LICENSE_LIMIT_EXCEEDED')){
                    exceptionText = 'You tried to assign more licenses than available. ' +' You tried to create '+ firstUPLs.size()+' licenses but only have '+ (pl[0].AllowedLicenses - pl[0].UsedLicenses) + ' licenses free.';
                }
            }
        }    
    }
}

}

test class

@istest

public class AssignPackageLicenseTest { @testSetup static void setup() { String profileName = 'System Administrator'; String userName = 'testuserLicense@testOrg.com';

    Profile profileId = [SELECT Id,Name FROM Profile WHERE Name = :profileName LIMIT 1];

    User testUser = new User(LastName = 'User',
                             FirstName='Test',
                             Alias = 'Utest',
                             Email = 'user.test@TestTelstra.com',
                             Username = userName,
                             ProfileId = profileId.id,
                             TimeZoneSidKey = 'GMT',
                             LanguageLocaleKey = 'en_US',
                             EmailEncodingKey = 'UTF-8',
                             LocaleSidKey = 'en_US'
                            );        
    insert testUser;
    System.debug('testUser>>>>'+testUser);
}
 static testMethod void userTest(){
     List<user> uList=new List<user>([select id,username from user where username='testuserLicense@testOrg.com' limit 1]);

   // AssignPackageLicense.assignLicenseByProfile(uList);
     //system.debug('u>>>>'+u);
     system.assertEquals('testuserlicense@testorg.com',uList[0].username);
     List<UserPackageLicense>u=new list<UserPackageLicense>([select userid from UserPackageLicense]);

 }
static testMethod void userTestcat(){
    try{
    List<user> uList=new List<user>([select id,username from user where username='testuserL3icense@testOrg.com' limit 1]);
    AssignPackageLicense.assignLicenseByProfile(uList);
    }
    catch(DMLException e) {
        //system.assertEquals(e.getMessage().contains('assign more'));
    }


 }

}

please suggest ,how can i cover try/catch block .coverage is bit low

2

Since a fair amount of code is in the catch block and you are not easily able to simulate exceptions from the DML operations I have two suggestions:

  1. Move the code out of the catch block into a separate method and write explicit tests for this method
  2. Use an abstraction in place of the DML operations (push these operations into a separate class that allows you to change the behaviour via subclassing, for example, and arrange for your production code to permit this to be swapped out for a test version).

For what you have here option 1 is easiest. Option 2 requires more infrastructure (e.g. a "factory method with dependency injection" approach) but is good if you have a lot of code that you want to be able to test with arbitrary DML "failures").

The "factory method with dependency injection" approach is one similar to this:

public virtual DMLOperations {
    private static Type instanceType = DMLOperations.class;
    public static void setType(Type instanceType) {
        this.instanceType = instanceType;
    }
    public static DMLOperations getInstance() {
        return (DMLOperations) instanceType.newInstance();
    }
    public virtual Database.SaveResult doInsert(sObject recordToInsert, Boolean allOrNone) {
        return Database.insert(recordToInsert, allOrNone);
    }
}

This then allows the production code to do something like:

try {
    //bulk insert
    DMLOperations.getInstance().doInsert(firstUPLs, true);
} catch (DmlException e) {

And your test can change the behaviour like:

@IsTest
public class AssignPackageLicenseTest {
    public class MyDMLOperations extends DMLOperations {
        public override Database.SaveResult doInsert(sObject recordToInsert, Boolean allOrNone) {
            // Throw exception, use JSON deserialize to create fake save results or whatever
        }
    }

    @IsTest
    static void exampleTest() {
        DMLOperations.setType(MyDMLOperations.class);

        // Do whatever testing you want
    }
}

BTW, your "getUsersWithProfile" method doesn't make sense. Since you only query the ID, you already have a list of users with ID being passed in so just use that original list. If you want to query other values, you should find that you can change this method as shown:

static List<User> getUsersWithProfile(List<User> users) {
    return [SELECT Id, X, Y, Z FROM User WHERE Id IN :users];
}
  • Is there any way to install package in Test class – sudhanshu Apr 25 at 4:45
  • Not that I am aware of. It also doesn't really make sense to do so since package installation can take quite a long time. – Phil W Apr 25 at 7:22
  • If my answer helps with your initial question please mark it. Thanks. – Phil W Apr 25 at 7:24

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.