+ Start a Discussion
Nidhi SoniNidhi Soni 

quick question on test class ?

I'm newbie to coding !
So very basic question when i write test class, do I need to specify each field I wrote in trigger ?
James LoghryJames Loghry
Hi Nidhi,

You'll want to test three different scenarios (at least) in your trigger, if you want an effective test:
1) If the fields are not populated.
2) If the fields are populated with junk or unexpected data.
3) The fields are populated as expected.

I typically separate these out into 3 different unit tests.

So for 2 and 3, your test may not break if you forget to fill the fields out (depends on your trigger), but you'll want to fill the fields out to produce a proper test.

Does that help and make sense?

- James
Nidhi SoniNidhi Soni
I just need to write test class for 100% code coverage.
Veena GopalVeena Gopal
Hi Nidhi,
it depends on what your trigger does. there is no such thing like using every field given
​in trigger. Test class is to test the functionality if the trigger written is working as expected.
given is a example for your reference.
trigger AccountDeletion on Account (before delete) {
   
    // Prevent the deletion of accounts if they have related contacts.
    for (Account a : [SELECT Id FROM Account
                     WHERE Id IN (SELECT AccountId FROM Opportunity) AND
                     Id IN :Trigger.old]) {
        Trigger.oldMap.get(a.Id).addError(
            'Cannot delete account with related opportunities.');
    }
    
}
 
The above trigger is on account object preventing account from getting deleted which has related opportunity.
In the test class they have set up the data. you can skip that if you already have a related opportunity account present.
Instead of writing a code for inserting. you can just write a soql query to obtain any one account id which has a connection with opportunity and write the code for deletion and check using system.assert.
@isTest
private class TestAccountDeletion {

    @isTest static void TestDeleteAccountWithOneOpportunity() {
        // Test data setup
        // Create an account with an opportunity, and then try to delete it
        Account acct = new Account(Name='Test Account');
        insert acct;
        Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       AccountId=acct.Id);
        insert opp;
        
        // Perform test
        Test.startTest();
        Database.DeleteResult result = Database.delete(acct, false);
        Test.stopTest();

        // Verify 
        // In this case the deletion should have been stopped by the trigger,
        // so verify that we got back an error.
        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
        System.assertEquals('Cannot delete account with related opportunities.',
                             result.getErrors()[0].getMessage());
    }
    
}

Let me know if you still have doubts in this.
Nidhi SoniNidhi Soni
Hi Veena !
I am in learning process. Here is the trigger I have written
trigger WarrantySummary on Case (before insert) {

        String endingStatement = 'Have a nice day!';
       for (Case myCase : Trigger.new){
           //Set up variables to use in the summary field.
            String purchaseDate           = myCase.Product_Purchase_Date__c.format();
            String createdDate            = Datetime.now().format();
            Integer warrantyDays          = myCase.Product_Total_Warranty_Days__c.intValue();
            Decimal warrantyPercentage    = (100 * (myCase.Product_Purchase_Date__c.daysBetween(Date.today())
                                              / myCase.Product_Total_Warranty_Days__c)).setScale(2);
            Boolean HasExtendedWarranty   = myCase.Product_Has_Extended_Warranty__c;

         //Populate summary field
         myCase.Warranty_Summary__c     = 'Product purchase on '  + purchaseDate + ''
                                        + ' and case created on '  + createdDate + '.\n'
                                        + ' Warranty is for '  + warrantyDays +''
                                        + ' days and is '  + warrantyPercentage + ' % through its warranty period.\n'
                                        + ' Extended warranty: '  + HasExtendedWarranty + '.\n'
                                        +  endingStatement;


}
}
Now I need to write test class for this trigger.
Veena GopalVeena Gopal
Hi Nidhi,
In this case you will have to fill all the fields correctly so that your field Warranty_Summary__c is filled correctly. This would be the correct way to test the trigger and it is quite simple to test. 
(you will just have to take an existing record from case.)

Since Warranty_Summary__c is a string or a text field for the sake of coverage you can fill anything and acheive 100% coverage by using 
System.assertNotEquals(null,mycase.Warranty_Summary__c); after moving a random statement to Warranty_Summary__c. but that would be incorrect testing.

For the fields to be filled correctly in real time is the responsibity of the validation rules of the object. 

Inside the test class method:
@isTest
private class Testmycasesummary {

    @isTest static void Testmycasesummaryfield() {
        // Test data setup
Case myCase = new Case();

myCase = [SELECT Product_Purchase_Date__c, Product_Total_Warranty_Days__c, Product_Has_Extended_Warranty__c FROM Case limit 1];



//you can use where clause if you are sure about the record you want to use for testing



String purchaseDate           = myCase.Product_Purchase_Date__c.format();
            
String createdDate            = Datetime.now().format();
            
Integer warrantyDays          = myCase.Product_Total_Warranty_Days__c.intValue();
            
Decimal warrantyPercentage    = (100 * (myCase.Product_Purchase_Date__c.daysBetween(Date.today())
                                              / myCase.Product_Total_Warranty_Days__c)).setScale(2);
            
Boolean HasExtendedWarranty   = myCase.Product_Has_Extended_Warranty__c;
//endingStatement if it is a part of the object will be filled automatically.


Test.startTest(); 

myCase.Warranty_Summary__c     = 'Product purchase on '  + purchaseDate + ''
                                        
+ ' and case created on '  + createdDate + '.\n'
                                        
+ ' Warranty is for '  + warrantyDays +''
                                        
+ ' days and is '  + warrantyPercentage + ' % through its warranty period.\n'
                                        
+ ' Extended warranty: '  + HasExtendedWarranty + '.\n'
                                        
+  endingStatement;

Test.stopTest();




system.assertEquals(null, purchaseDate); 

System.assertNotEquals(null,createdDate);

System.assertNotEquals(0,warrantyDays);

System.assertNotEquals(0,warrantyPercentage);

System.assertNotEquals(null,HasExtendedWarranty);

}
}
you can also use a system.debug for each of the variables and also for myCase.Warranty_Summary__c to check the value. 
Nidhi SoniNidhi Soni
Hi Veena,
I got this error while testing

User-added image
Am I missing sth ???
Amit Chaudhary 8Amit Chaudhary 8
Hello Nidhi

I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm

Pleasse check below post sample test class
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

You write a test class for this the same way that you would any other:

- Set up some data for the Trigger to access (insert case object)
- Instantiate the Controlller-
- Execute a method/methods
- Verify the behaviour with asserts.

Sample code for you
@isTest
private class Testmycasesummary {

    @isTest static void Testmycasesummaryfield() 
	{
	
		Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email');
		insert cas;
		
		List<Case> lstCase = [select id,Warranty_Summary__c      from case where id in :cas.id ];
		System.assert(lstCase[0].Warranty_Summary__c != null);
		
	}
}

Let us know if this will help you

 
D-CoderD-Coder
Here is your test class with 100% code coverage :
 
@isTest
public class TestCaseTrigger {
    static testMethod void insertCase() {
        
        Case c = new Case();
//Create new case instance
        
        C.Status = "New";
        C.Origin = "Phone";
 //cover case required fields 

        insert c;
//insert case - All your fields will be populated automatically via trigger
        
        
    }
}


 
Veena GopalVeena Gopal
Hi Nidhi,
Do you have valid records in your case object for testing?
Which line is giving the error?
Veena
 
Amit Chaudhary 8Amit Chaudhary 8
Hi Veena,

Issue coming in your record because you are trying to query record in test class without creating any record.
Case myCase = new Case();

myCase = [SELECT Product_Purchase_Date__c, Product_Total_Warranty_Days__c, Product_Has_Extended_Warranty__c FROM Case limit 1];

for nidhi test class we just need to insert case object with all required field. Like below
@isTest
private class Testmycasesummary {

    @isTest static void Testmycasesummaryfield() 
	{
	
		Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); // add all required field
		insert cas;
		
		List<Case> lstCase = [select id,Warranty_Summary__c      from case where id in :cas.id ];
		System.assert(lstCase[0].Warranty_Summary__c != null);
		
	}
}

Hi Nidhi,

Please test above code and let us know if that will work