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
Liz Gibbons 16Liz Gibbons 16 

Test class for Batch Class: help needed

Hello,

I have a batch class for converting Contacts into Community Users. My test class keeps failing and I can't seem to get more than 37% coverage. The error I get from the failed tests is:
Error Message: System.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.ConvertToCommUsers.execute: line 23, column 1
Class.TestConvertTOCommUsers.test: line 20, column 1
Any help would be greatly appreciated!

The class
global class ConvertToCommUsers implements Database.Batchable<sObject> {
	global String query;   
    	global Database.QueryLocator start(Database.BatchableContext BC){
        	query = 'SELECT	Id, FirstName, LastName, Name, Email, AccountId FROM Contact WHERE RecordType.Name = \'Learner\' AND Id NOT IN (SELECT ContactId FROM User)'; 
        
        	return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Contact> scope){
        String Passwd;
        Profile LPCommPf = [SELECT Id, Name FROM Profile WHERE Name = 'Learner Profile Community User' LIMIT 1];
        List<Messaging.SingleEmailMessage> setPWs = new List<Messaging.SingleEmailMessage>();
        List<User> learners = new List<User>();
        
        for (Contact c : scope){
           User u = new User();
            	u.FirstName = c.FirstName;
                u.LastName = c.LastName;
                u.ContactId = c.Id;
                u.Email = c.Email;
                u.Username = c.Email;
                u.CommunityNickname = c.Email.Trim().toLowerCase();
                u.Alias = c.Name.abbreviate(8);
                u.ProfileId = LPCommPf.id;
                u.LocaleSidKey = 'en_US';
                u.TimeZoneSidKey = 'America/New_York';
                u.LanguageLocaleKey = 'en_US';
                u.EmailEncodingKey = 'UTF-8';
                String pwd = Passwd;
            
            learners.add(u);
        } 
            
        	insert learners;
        
        for( User s : learners){
            
            Messaging.SingleEmailMessage setPW = new Messaging.SingleEmailMessage();
        	List<String> sendTo = new List<String>();
        	sendTo.add(s.Email);
        	setPW.setToAddresses(sendTo);
        	setPW.setSenderDisplayName('info@digitalonramps.com');
        	setPW.setSenderDisplayName('Digital On-Ramps');
        	setPW.setTemplateId('00X17000000E35e'); 
        	setPW.setTargetObjectId(s.Id);
        	setPW.setSaveAsActivity(false);
            
            setPWs.add(setPW);
            
        }
        Messaging.sendEmail(setPWs);
    }
    
    global void finish(Database.BatchableContext BC){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'meg372@drexel.edu'});
        	mail.setReplyTo('batch@digitalonramps.com');
        	mail.setSenderDisplayName('Batch Processing');
        	mail.setSubject('Batch Process Complete');
        	mail.setPlainTextBody('Batch Process has completed');
        
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        
    }

}

The test class
@isTest
private class TestConvertToCommUsers {
    static testmethod void test(){
        Database.QueryLocator QL;
        Database.BatchableContext BC;
        List<Contact> scope = new List<Contact>();
        
            Contact c = new Contact(FirstName= 'Test', LastName = 'Test', Email='testtest@dor.com',  RecordTypeId = '012G0000001QJQc');
            scope.add(c);
        
        	insert scope;
        	 
    
    
        Test.startTest();
         
        ConvertToCommUsers comm = new ConvertToCommUsers();
       	comm.query = 'SELECT Id, FirstName, LastName, Name, Email, AccountId FROM Contact';
        QL = comm.start(BC);
        comm.execute(BC, scope);
        comm.finish(BC);

        Test.stopTest();       
    }
}




Thanks in advance!
Liz
Best Answer chosen by Liz Gibbons 16
Prem Anandh 1Prem Anandh 1
Hi Liz, 

Please check below code and let me know if you are facing any problem 
 
@isTest
private class TestConvertToCommUsers {
    static testmethod void test(){
            
            List<RecordType> lstRecordType = new List<RecordType>([SELECT Id,Name,SobjectType FROM RecordType WHERE SobjectType = 'Contact' AND Name = 'Learner']);

            if(!lstRecordType.isEmpty())
            {

                Account objAccount = new Account(Name='testAccount');
                insert objAccount;

                Contact objContact = new Contact(AccountId = objAccount.Id, FirstName= 'Test', LastName = 'Test', Email='testtest@dor.com',  RecordTypeId = lstRecordType[0].Id);  

                insert objContact;        
            }   
    
        Test.startTest();
        
        Database.executeBatch(new ConvertToCommUsers(), 1);

        Test.stopTest();       
    }
}

Thanks,
Prem Anandh

All Answers

Prem Anandh 1Prem Anandh 1
Hi Liz, 

Please check below code and let me know if you are facing any problem 
 
@isTest
private class TestConvertToCommUsers {
    static testmethod void test(){
            
            List<RecordType> lstRecordType = new List<RecordType>([SELECT Id,Name,SobjectType FROM RecordType WHERE SobjectType = 'Contact' AND Name = 'Learner']);

            if(!lstRecordType.isEmpty())
            {

                Account objAccount = new Account(Name='testAccount');
                insert objAccount;

                Contact objContact = new Contact(AccountId = objAccount.Id, FirstName= 'Test', LastName = 'Test', Email='testtest@dor.com',  RecordTypeId = lstRecordType[0].Id);  

                insert objContact;        
            }   
    
        Test.startTest();
        
        Database.executeBatch(new ConvertToCommUsers(), 1);

        Test.stopTest();       
    }
}

Thanks,
Prem Anandh
This was selected as the best answer
Liz Gibbons 16Liz Gibbons 16
Thanks Prem! That works!
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class.
@isTest
private class TestConvertToCommUsers 
{
    static testmethod void test()
	{
	
		Id p = [select id from profile where name='Partner Community User'].id; // Please add community profile Name here

        Account ac = new Account(name ='TEst') ;
        insert ac; 
        
		Id contRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Learner').getRecordTypeId();
		
        Contact con = new Contact(LastName ='TEst',AccountId = ac.Id , recordTypeid = contRecordTypeId );
        insert con;  

        Contact con1 = new Contact(LastName ='TEst1',AccountId = ac.Id , recordTypeid = contRecordTypeId );
        insert con1;  
		
        User user = new User(alias = 'test123', email='test123@noemail.com',
                emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                ContactId = con.Id,
                timezonesidkey='America/Los_Angeles', username='tester@noemail.com');
        insert user;
    
        Test.startTest();
			ConvertToCommUsers comm = new ConvertToCommUsers();
			database.executebatch(comm);
        Test.stopTest();       
    }
}
Please check below post for test classes.
1) http://amitsalesforce.blogspot.in/search/label/Test%20Class
2) http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html


Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks
Amit Chaudhary