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
Øyvind Borgersen 10Øyvind Borgersen 10 

Issues with test class coverage (62%)

Hi,

I have a simple trigger and test class where I need some help to get from the 62% coverage and up to at least 90%.  The lines which are not covered are the ones after the 'IF' statement. 

Can someone please help me with the remaining test class code?

The trigger is as follows:

trigger contactCreateCommunityUser on Contact (before insert) {
    String currentuser = UserInfo.getUserId();
    String emailAddress = UserInfo.getUserEmail();
    
    ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
    List <User> systemAdm = [SELECT Id
                               FROM User
                              WHERE Name like '%Systemadministrator%'];
    system.debug('Systemadmin ID ' + systemAdm);
    If(contactId != null) {
        ID AccID = [Select AccountID from Contact where id =: contactid].AccountId;
        for(Contact con : trigger.new){
            con.OwnerId = systemAdm.get(0).Id;
        }
    }
}


Test class:
@isTest
private class contactCreateCommunityUserTest {       
    static testmethod void contactCreateCommunity() {
        Account acc = [SELECT Id
                        FROM  Account
                        Limit 1];
        
        Contact con = new contact();
        con.lastName = 'TestLastName';
        con.AccountId = acc.Id;
        Insert con;
    }
}
Greg HGreg H
I am not quite following your logic for assigning the Owner of a new Contact within your trigger. Nonetheless, you need to create data for use in your test. Since your Using Communities the setup data is a little more complicated than simply creating an Account and related Contacts. You need the Community/Partner Account, the Community/Partner Contact, the Community/Partner User record tied to the Contact. Then you need the Contacts for use in your trigger context testing. A lot more setup for such a little trigger but necessary. This isn't exactly correct but it should get you started:
@isTest
private class contactCreateCommunityUserTest {
	
    //tests contactCreateCommunityUser.trigger
    @isTest //defines method for use during testing only
    static void triggerLogic() {
        Profile randomProfile = [SELECT Id FROM Profile WHERE UserType = 'PowerPartner' LIMIT 1]; //grab a Community Profile.Id
        Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator']; //grab System Admin profile
        //create account for Community users
        List<Account> partnerAccounts = new List<Account>();
        partnerAccounts.add(new Account(Name = 'Partner Community Account'));
        insert partnerAccounts;
        //create some Contacts because we want to create portal users we are required to provide a corresponding contactId
        List<Contact> partnerContacts = new List<Contact>();
        partnerContacts.add(new Contact(AccountId = partnerAccounts[0].Id, Email = 'demo.user@yourdomain.com', FirstName = 'Demo2', LastName = 'User2'));
        insert partnerContacts;
        //create the User
        List<User> newUsers = new List<User>();
        newUsers.add(new User(Alias = 'test01', ContactId = partnerContacts[0].Id, Email = 'demo.user@yourdomain.com', EmailEncodingKey = 'ISO-8859-1', FirstName = 'Demo1', IsActive = true, LanguageLocaleKey = 'en_US', LastName = 'Partner', LocaleSidKey = 'en_US', MobilePhone = '(303) 555-0000', Phone = '(303) 555-2222', ProfileId = randomProfile.Id, TimeZoneSidKey = 'America/New_York', Username = 'demo.user@yourdomain.com')); //
        newUsers.add(new User(Alias = 'test02', Email = 'system.admin@yourdomain.com', EmailEncodingKey = 'ISO-8859-1', FirstName = 'Demo2', IsActive = true, LanguageLocaleKey = 'en_US', LastName = 'Systemadministrator', LocaleSidKey = 'en_US', MobilePhone = '(303) 555-1111', Phone = '(303) 555-2222', ProfileId = adminProfile.Id, TimeZoneSidKey = 'America/New_York', Username = 'system.admin@yourdomain.com'));
        newUsers.add(new User(Alias = 'test03', Email = 'another.user@yourdomain.com', EmailEncodingKey = 'ISO-8859-1', FirstName = 'Demo3', IsActive = true, LanguageLocaleKey = 'en_US', LastName = 'Admin', LocaleSidKey = 'en_US', MobilePhone = '(303) 555-3333', Phone = '(303) 555-2222', ProfileId = adminProfile.Id, TimeZoneSidKey = 'America/New_York', Username = 'another.user@yourdomain.com'));
        insert newUsers;
        //now you have the underlying Community setup created...
        //execute the remainder of the logic as a User that was just created
        System.runAs(newUsers[2]) {
            //insert an account
            List<Account> accounts = new List<Account>();
            accounts.add(new Account(Name = 'Test Corp'));
            insert accounts;
            
            Test.startTest(); //denote testing context
            
            //create a Contact
            List<Contact> contacts = new List<Contact>();
            contacts.add(new Contact(AccountId = accounts[0].Id, FirstName = 'Tess', LastName = 'Dachshund'));
            insert contacts;
            
            //validate your logic here...
            
            Test.stopTest(); //revert from testing context
        }
    }

}
Good luck.
-greg
Maharajan CMaharajan C
Try the below test class:

You will get 100% coverage

@isTest
private class contactCreateCommunityUserTest {       
    static testmethod void contactCreateCommunity() {
        List<user> userList = new List<user>();
        Account portalAccount1 = new Account(
            Name = 'TestAccount'
        );
        Database.insert(portalAccount1);
        
        Contact contact1 = new Contact(
            FirstName = 'Test',
            Lastname = 'con1',
            AccountId = portalAccount1.Id,
            Email = 'test@test.com'
        );
        Database.insert(contact1);
        
        //Create user for the contact
        Profile portalProfile = [SELECT Id FROM Profile WHERE Name = 'Partner Community User' Limit 1];
        Profile p = [SELECT Id FROM profile WHERE name='System Administrator']; 
        User user1 = new User(
            Username = 'testportal123test@test.com',
            ContactId = contact1.Id,
            ProfileId = portalProfile.Id,
            Alias = 'test123',
            Email = 'test12345@test.com',
            EmailEncodingKey = 'UTF-8',
            LastName = 'Kumar',
            CommunityNickname = 'test12345',
            TimeZoneSidKey = 'America/Los_Angeles',
            LocaleSidKey = 'en_US',
            LanguageLocaleKey = 'en_US'
        );
        User saUser = new User(alias = 'newUser1', 
                               email='accuser@testorg.com', 
                               emailencodingkey='UTF-8', lastname='Systemadministrator', 
                               languagelocalekey='en_US', 
                               localesidkey='en_US', profileid = p.Id, 
                               timezonesidkey='America/Los_Angeles', 
                               username='sauser123@testorg.com');
        userList.add(user1);
        userList.add(saUser);
        Database.insert(userList);        
        
        system.runAs(user1)
        {
            Contact contact2 = new Contact(
                FirstName = 'Test',
                Lastname = 'Con2',
                Email = 'test@testt.com'
            );
            Database.insert(contact2);
        }
    }
}

Thanks,
Maharajan.C
Øyvind Borgersen 10Øyvind Borgersen 10
Hi Maharajan,

I get the following error:  System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []
Class.contactCreateCommunityUserTest.contactCreateCommunity: line 52, column 1

This referes to the last section where user1 is addding contactvalues.