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
Shannon Andreas 1Shannon Andreas 1 

Need better coverage for trigger...ughhh!

Wrote a trigger. Getting 33% code coverage and cannot deploy to production. Any help in making my test class code better?

Thanks!

trigger CreateContract on Opportunity (after insert) {
    List<Contract> ctr = new List<Contract>();
    
      for(Opportunity o : Trigger.new) {
        if(o.Ready_for_Contract__c == true) {
          Contract c = new Contract(Name = o.Name,
             Status = 'Draft',
             Total_Contract_Value__c = o.Amount,
             StartDate = o.Contract_Start_Date__c,
             Payment_Status__c = 'Ready to be Invoiced',
             Account = o.Account,
             Opportunity_Name__c = o.Id);
         ctr.add(c);
         }
      insert ctr;
      }
}


TEST Class
@isTest
private class TestClassCreateContractTrigger 
{
    static testMethod void validateCreateContract() 
    {   
       Account a = new Account(
       Name = 'Test Account');
    insert a;

       Opportunity o = new Opportunity(
       Name = 'Test Opp',
       CloseDate = System.Today(),
       AccountId = a.Id,
       StageName = 'Signed / Closed Sale',
       Amount = decimal.valueof('6995'));
    insert o;
    
       Contract c = new Contract(
            Name='Test Contract',
            Status = 'Draft',
            Total_Contract_Value__c = o.Amount,
            StartDate = System.Today(),
            Payment_Status__c = 'Ready to be Invoiced',
            AccountId = o.AccountId,
            Opportunity_Name__c = o.Id);
       insert c;
       
      }
}
 
William TranWilliam Tran
Try adding Ready_for_Contract__c = true, to your opportunity:

Here's the code with that in there.

Thx
 
TEST Class
@isTest
private class TestClassCreateContractTrigger 
{
    static testMethod void validateCreateContract() 
    {   
       Account a = new Account(
       Name = 'Test Account');
    insert a;

       Opportunity o = new Opportunity(
       Name = 'Test Opp',
       Ready_for_Contract__c = true,
       CloseDate = System.Today(),
       AccountId = a.Id,
       StageName = 'Signed / Closed Sale',
       Amount = decimal.valueof('6995'));
    insert o;
    
       Contract c = new Contract(
            Name='Test Contract',
            Status = 'Draft',
            Total_Contract_Value__c = o.Amount,
            StartDate = System.Today(),
            Payment_Status__c = 'Ready to be Invoiced',
            AccountId = o.AccountId,
            Opportunity_Name__c = o.Id);
       insert c;
       
      }
}

 
Amit Chaudhary 8Amit Chaudhary 8
Hi Shannon Andreas 1,

I found below issue in your test class
1) Ready_for_Contract__c was not set
2) No need to create contract record in Trigger
3) Assert was missing

Please check below test class.
@isTest
private class TestClassCreateContractTrigger 
{
    static testMethod void validateCreateContract() 
    {   
       Account acc = new Account();
	   acc.Name ='TestName';
	   insert acc;

		Opportunity o = new Opportunity(
		Name = 'Test Opp',
		Ready_for_Contract__c = true,
		CloseDate = System.Today(),
		AccountId = acc.Id,
		StageName = 'Signed / Closed Sale',
		Amount = decimal.valueof('6995'));
		
		Test.StartTest();
		
			insert o;
			List<Contract> lstContr = [select id from contract where Opportunity_Name__c =:o.id];
			//System.assertNotEquals(lstContr,null);
			
		Test.StopTest();
      }
}

Please check below blog on test classes. I hope that will help u
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
 
Vishal_GuptaVishal_Gupta
Hi Shannon,

I found that in your trigger contract are inserting in for loop and will cause governor limit issue in large volume of data, please change your trigger with below one :

trigger CreateContract on Opportunity (after insert)
{
    List<Contract> ctr = new List<Contract>();
    
      for(Opportunity o : Trigger.new) 
      {
        if(o.Ready_for_Contract__c == true) 
        {
             Contract c = new Contract(Name = o.Name,
             Status = 'Draft',
             Total_Contract_Value__c = o.Amount,
             StartDate = o.Contract_Start_Date__c,
             Payment_Status__c = 'Ready to be Invoiced',
             Account = o.Account,
             Opportunity_Name__c = o.Id);
             ctr.add(c);
         }
      }
      insert ctr;
}

and you can use the test class provided by Amit Chaudhary.

Please let me know if I can help you more.

Thanks,
Vishal
Shannon Andreas 1Shannon Andreas 1
Thanks for your comments guys!

Here is my feedback:

1.) When I tried to change the test class to what Amit published here, I received the following error on save:

[Error] Error: Compile Error: Invalid field initializer: acc.Name at line 7 column 8

2.) I removed the acc and it saved. However, I received the following error when I ran the test:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateContract: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [AccountId]: [AccountId]

Trigger.CreateContract: line 19, column 1: []

Thanks,

Shannon


 
William TranWilliam Tran
Did you try my suggestion?

Thx
Amit Chaudhary 8Amit Chaudhary 8
Plese follow below step :-

Step 1:- Please modify your Trigger according to Vishal comment
trigger CreateContract on Opportunity (after insert)
{
    List<Contract> ctr = new List<Contract>();
    
      for(Opportunity o : Trigger.new) 
      {
        if(o.Ready_for_Contract__c == true) 
        {
             Contract c = new Contract(Name = o.Name,
             Status = 'Draft',
             Total_Contract_Value__c = o.Amount,
             StartDate = o.Contract_Start_Date__c,
             Payment_Status__c = 'Ready to be Invoiced',
             Account = o.Account,
             Opportunity_Name__c = o.Id);
             ctr.add(c);
         }
      }
      insert ctr;
}
Step 2:- Then try below Test class
@isTest
private class TestClassCreateContractTrigger 
{
    static testMethod void validateCreateContract() 
    {   
		Account a = new Account(
		   Name = 'Test Account');
		insert a
	
		Opportunity o = new Opportunity(
		Name = 'Test Opp',
		Ready_for_Contract__c = true,
		CloseDate = System.Today(),
		AccountId = a.Id,
		StageName = 'Signed / Closed Sale',
		Amount = decimal.valueof('6995'));
		
		Test.StartTest();
		
			insert o;
			List<Contract> lstContr = [select id from contract where Opportunity_Name__c =:o.id];
			//System.assertNotEquals(lstContr,null);
			
		Test.StopTest();
      }
}
Please let us know if this will help u

Thanks
Amit Chaudhary


 
Shannon Andreas 1Shannon Andreas 1
William,

Yes, I did and it did not work.

Amit,

Same test error:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateContract: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [AccountId]: [AccountId]

Trigger.CreateContract: line 19, column 1: []

But I am getting 100% coverage!

 
Amit Chaudhary 8Amit Chaudhary 8
Please modify your trigger like below code
trigger CreateContract on Opportunity (after insert)
{
    List<Contract> ctr = new List<Contract>();
    
      for(Opportunity o : Trigger.new) 
      {
        if(o.Ready_for_Contract__c == true) 
        {
             Contract c = new Contract(Name = o.Name,
             Status = 'Draft',
             Total_Contract_Value__c = o.Amount,
             StartDate = o.Contract_Start_Date__c,
             Payment_Status__c = 'Ready to be Invoiced',
             AccountId = o.Account,
             Opportunity_Name__c = o.Id);
             ctr.add(c);
         }
      }
      insert ctr;
}
Please let us know if that will help you

Thanks
Amit Chaudhary

 
Shannon Andreas 1Shannon Andreas 1
Okay...so I changed the code slightly to below:

trigger CreateContract on Opportunity (after insert)
{
    List<Contract> ctr = new List<Contract>();
    
      for(Opportunity o : Trigger.new) 
      {
        if(o.Ready_for_Contract__c == true) 
        {
             Contract c = new Contract(Name = o.Name,
             Status = 'Draft',
             Total_Contract_Value__c = o.Amount,
             StartDate = o.Contract_Start_Date__c,
             Payment_Status__c = 'Ready to be Invoiced',
             AccountId = o.AccountId,
             Opportunity_Name__c = o.Id);
             ctr.add(c);
         }
      }
      insert ctr;
}

And it passsed! Also have 100% coverage.

Now to see if it actually works.

Will let you know and mark this post when confirmed.
Shannon Andreas 1Shannon Andreas 1
Okay...so even with the "green light" from a code perspective, the contract is not being created.

I checked the box on the Oppty (Ready for Contract) and saved. Nothing happens. No contract created. I checked the related list on the Oppty as well as the Contract object list view to see if a contract has been created and I cannot see anything. 

I also ran a debug log on myself and I don't even see the trigger information in the logs. 

Help!
Shannon Andreas 1Shannon Andreas 1
So it looks like the contracts are being created somewhere. They are just not showing up in the object. How do I know? Because when I manually created a contract, the different between the last contract number (645) is the difference between the number of opptys I marked "Ready for Contract" and the manual contract (653). Where are they going? How do I find them?
Amit Chaudhary 8Amit Chaudhary 8
Please try to debug the below code.
trigger CreateContract on Opportunity (after insert)
{
    List<Contract> ctr = new List<Contract>();
    
      for(Opportunity o : Trigger.new) 
      {
        if(o.Ready_for_Contract__c == true) 
        {
             Contract c = new Contract(Name = o.Name,
             Status = 'Draft',
             Total_Contract_Value__c = o.Amount,
             StartDate = o.Contract_Start_Date__c,
             Payment_Status__c = 'Ready to be Invoiced',
             AccountId = o.Account,
             Opportunity_Name__c = o.Id);
             ctr.add(c);
         }
      }
	  if(ctr.size() > 0)
	  {
			System.debug('-ctr------->'+ctr.size());
			insert ctr;
	  }	
}
Also please chec contract under account ( Opportunity account)

Please let us know if this will help u

 
Shannon Andreas 1Shannon Andreas 1
Amit,

I made your suggested change and I still cannot see where it shows up in the debug log? What am I doing wrong?
Amit Chaudhary 8Amit Chaudhary 8
Yes please check log in debug log for below line
-ctr------->
Shannon Andreas 1Shannon Andreas 1
Okay...so it started working when I changed the trigger to an before update or after update. Go figure! Unfortunately, as you know, that created another problem. Formula fields and some other fields did not insert correctly. The other problem is the trigger fires EVERY time I edit the opportunity and resave. I know that can be fixed with another line of code. If you can help with these issues, that would be great.

Also, I did not see that line in the debugger.

Thanks