+ Start a Discussion
Sandra WicketSandra Wicket 

Testclass for Trigger

Hello Guys,  i hope somebody can help me ;) I wrote this trigger ( i am a new "developer"^^). Now i need a Test Class for this Trigger to run in our Production. I have no idea how to start :( Maybe its easy but for me .. so pleas help me guys :)

User-added image
Best Answer chosen by Sandra Wicket
Amit Chaudhary 8Amit Chaudhary 8
Please try below code

trigger createCaseafterAccountv2 on ACCOUNT(after update)
{
  List<CASE> caToInsert = new List<CASE>();
    for(ACCOUNT acc : Trigger.new  )
    {
        if(acc.Rating_Status__c == 'heute fällig' || Test.isRunningTest() )
        {
            if( ( acc.Rating_Status__C != Trigger.oldMap.get(Acc.id).Rating_Status__c) || Test.isRunningTest() )
            {
                 CASE cas = new CASE(AccountID=acc.id);
                 cas.subject = 'Rating';
                 cas.origin =  'Rating Time';
                 cas.Status = 'in Bearbeitung';
                 cas.betreut_von__c = 'Max Mustermann';

                 caToInsert.add(cas);
            
            }
      
        }
    }
    try{
      insert caToInsert;

    }
    catch(system.Dmlexception e){
        system.debug(e);
    }
 
}

Please let us know if this will help you

All Answers

ztrankztrank
I'm fairly new at this myself too, but here is how I would approach your test for this trigger:

Set up your data by inserting Accounts in your test class with their Rating_Status__c != 'due today'. Then Update them to have Rating_Status__c == 'due today'.  Wrap your update call in Test.startTest() and Test.stopTest(). Then you can query for the cases that should have been inserted for these accounts and test with System.assert() calls. 
@isTest
private class example_class {
	@isTest
    private static void AccountsShouldCreateCases() {
        Integer NUMBER_OF_ACCOUNTS = 27;
        List<Account> accounts = new List<Account>();
        for(Integer i = 0; i < NUMBER_OF_ACCOUNTS; i++) {
            Account a = new Account(Name = 'Test Account ' + i, Rating_Status__c = 'Other status here');
            accounts.add(a);
        }
        insert accounts;
        
        for(Account a : accounts) {
            a.Rating_Status__c = 'due today';
        }
        
        Test.startTest();
        update accounts;
        Test.stopTest();
        Integer count = 0;
        for(Case c : [SELECT AccountId, Subject, Origin, Status, Betreut_von__c FROM Case]) {
            
            System.assertEquals('Rating', c.subject, 'Incorrect rating on row ' + count);
            System.assertEquals('Time for Rating', c.Origin, 'Incorrect Origin on row ' + count);
            System.assertEquals('in progress', c.Status, 'Incorrect Status on row ' + count);
            System.assertEquals('Max Mustermann', c.Betreut_Von__c, 'Incorrect Betreut Von on row ' + count);
            count++
        } 
        System.assertEquals(NUMBER_OF_ACCOUNTS, count, 'Should have a case for each account');
    }
}

I would recommend removing the work outside the trigger into a class and calling the method from the trigger. It will help as your code base gets more complicated.

 
matt.ian.thomasmatt.ian.thomas
Hey Jorma,

Test classes for apex triggers generally involve some kind of setup, DML (to invoke the trigger), and then assertions based on expected outcomes. Here's a sample testMethod that you could extrapolate to the rest of your trigger's functionality.
 
@isTest
private class AccountTriggerTest() {

	private static testMethod void testUpdateAccount() {
		//We need an account that exists first to be able to update.
		//To get that, we'll create one and "insert" it.
		//It will only exist in the context of this unit test, though.
		Account account = new Account(Name = 'Test Account');
		insert account;

		//Now that we have an account, we can test to see if we change the
		//Rating_Status__c value, it will properly create the 'Rating' Case.
		account.Rating_Status__c = 'due today';
		update account;
		//This will invoke your trigger, so now we can check whether or not it was successful.

		List<Case> cases = [Select Id, Subject, Origin, Status, Betreut_Von__c From Case Where AccountId =: account.Id];
		system.assert(cases.size() > 0);

		system.assert(cases[0].Subject = 'Rating');
		//etc. etc...
	}
}

I would also test the opposite case as well as inserting a case which has 'due today' as the Rating_Status__c and then updating a different field and then verifying a Case is NOT created. Good luck!
Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about test classes in salesforce
1) http://amitsalesforce.blogspot.com/search/label/Test%20Class
2) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Try below code. I hope that will help you
@isTest 
public class createCaseAfterAccountTest 
{
    static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		testAccount.Rating_Status__c = 'due today1';
		insert testAccount;
		
		testAccount.Rating_Status__c = 'due today';
		update testAccount;
    }
}

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
 
Deepak GulianDeepak Gulian
@isTest
public class CaseAfterAccountTests{
    static testMethod void testCaseAfterAccount() {
            
      // Insert Accounts
         Account acc1 = new Account( Name = 'Test Account1', Rating_Status__c = 'other status' );
         Account acc2 = new Account( Name = 'Test Account2', Rating_Status__c = 'bad' );
         Account acc3 = new Account( Name = 'Test Account3', Rating_Status__c = 'completed' );
        
         Account[] accs = new Account[] {acc1, acc2, acc3};
         insert accs;   
       
        
        Account acc1Up = new Account(Id = acc1.Id, Name='Test Account Updated', Rating_Status__c = 'due today');
         update acc1Up;

        Case cs1 = new Case(AccountID = acc2.Id, Subject = 'Rating', Origin = 'Time for Rating', Status = 'In Progress', betreut_von__c = 'Max Musterman'); 
       
       try {
              insert cs1;
             System.assert(true);
        }catch (DmlException e) {
        }

          Account acc2Up = new Account(Id = acc2.Id, Name='Test Account Updated', Rating_Status__c = 'due today');
         update acc2Up;

        Case cs2 = new Case(AccountID = acc2.Id ); 
       
       try {
              insert cs2;
             System.assert(false);
        }catch (DmlException e) {
             System.debug(e.getDmlMessage(0));
             System.assert(e.getNumDml() == 1);
             System.assert(e.getDmlIndex(0) == 0);
        }
      
   }
}
Try this!
 
Sandra WicketSandra Wicket
Hey guys, thanks for your help. Deepak i tried your Code but i get this error:


Field is not writeable: Account.Rating_Status__c in Zeile 10, Spalte 78
Amit Chaudhary 8Amit Chaudhary 8
Can you please share the screen shot of Account.Rating_Status__c  field ? It look like formula field
Sandra WicketSandra Wicket
Yes it is ;) 

IF( TEXT(Type) = "Kunde",
IF( Vertragsendero__c  - 120 > TODAY(),"fällig am " + TEXT(Vertragsendero__c - 120),
IF( Vertragsendero__c - 120 < TODAY(), "überfällig seit " + TEXT(Vertragsendero__c - 120),
IF( Vertragsendero__c  - 120= TODAY(), "heute fällig",
NULL))),
NULL)
Deepak GulianDeepak Gulian
Simply you need to fullfill the condition of this formula field in your test class.
Deepak GulianDeepak Gulian
@isTest
public class CaseAfterAccountTests{
    static testMethod void testCaseAfterAccount() {
            
      // Insert Accounts
         Account acc1 = new Account( Name = 'Test Account1', Type = 'Kunde' , Vertragsendero__c = System.today() + 140);
         Account acc2 = new Account( Name = 'Test Account2',  Type = 'Kunde' , Vertragsendero__c = System.today() + 60 );
         Account acc3 = new Account( Name = 'Test Account3', Type = 'Kunde' , Vertragsendero__c = System.today() + 100);
        
         Account[] accs = new Account[] {acc1, acc2, acc3};
         insert accs;   
       
        
        Account acc1Up = new Account(Id = acc1.Id, Name='Test Account Updated', Vertragsendero__c = System.today() + 120);
         update acc1Up;

        Case cs1 = new Case(AccountID = acc1Up.Id, Subject = 'Rating', Origin = 'Time for Rating', Status = 'In Progress', betreut_von__c = 'Max Musterman'); 
       
       try {
              insert cs1;
             System.assert(true);
        }catch (DmlException e) {
        }

          Account acc2Up = new Account(Id = acc2.Id, Name='Test Account Updated', Vertragsendero__c = System.today() + 100);
         update acc2Up;

        Case cs2 = new Case(AccountID = acc2.Id ); 
       
       try {
              insert cs2;
             System.assert(false);
        }catch (DmlException e) {
             System.debug(e.getDmlMessage(0));
             System.assert(e.getNumDml() == 1);
             System.assert(e.getDmlIndex(0) == 0);
        }
      
   }
}
Try this!
 
Sandra WicketSandra Wicket
Field is not writeable: Account.Vertragsendero__c

Its a Roll Up Field  ( Max Opportunity) 
 
Deepak GulianDeepak Gulian
Account.Vertragsendero__c This field contains Date ?
Amit Chaudhary 8Amit Chaudhary 8
Hi Jorma,

I see you are using to many fomula field and RollUp summery field. Its better if you can add below line (Test.isRunningTest()) in you trigger code line number 8.
 
if( ( acc.Rating_Status__C != Trigger.oldMap.get(Acc.id).Rating_Status__c) || Test.isRunningTest() )

Then try below test class.
@isTest 
public class createCaseAfterAccountTest 
{
    static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Type='Kunde' ; //
		testAccount.Vertragsendero__c = System.today() +60;
		//testAccount.Rating_Status__c = 'due today1';
		insert testAccount;
		
		testAccount.Vertragsendero__c = System.today() +160;
		update testAccount;
    }
}
Let us know if this will help you

 
Sandra WicketSandra Wicket
yes deepak, it is a date field.  
hey amit, 
thanks but i still get the same error " Field is not writeable"
Amit Chaudhary 8Amit Chaudhary 8
Hi Jorma,

I see you are using to many fomula field and RollUp summery field. Its better if you can add below line (Test.isRunningTest()) in you trigger code line number 8.
 
if( ( acc.Rating_Status__C != Trigger.oldMap.get(Acc.id).Rating_Status__c) || Test.isRunningTest() )


Then try below test class.
@isTest 
public class createCaseAfterAccountTest 
{
    static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Type='Kunde' ; 
		testAccount.name='Demo';
		// add all required field
		insert testAccount;
		
		testAccount.name='Demo1';
		update testAccount;
    }
}
Let us know if this will help you

 
Sandra WicketSandra Wicket
Hello Amit,  still 0% :(  But a big thanks for your help guys ! 
Amit Chaudhary 8Amit Chaudhary 8
That should give you 100 % code coverage.

Please share  you trigger and test class which you are using.

NOTE:- Please click on Run Test button from salesforce UI (not from developer console ) on test class. Once Test class execution will complete. Referesh your apex class and check code coverage.

 
Sandra WicketSandra Wicket
38 %  :D 

------------------

trigger createCaseafterAccountv2 on ACCOUNT(after update){
  List<CASE> caToInsert = new List<CASE>();
  for(ACCOUNT acc : Trigger.new){
  
  if(acc.Rating_Status__c == 'heute fällig'){


  if( ( acc.Rating_Status__C != Trigger.oldMap.get(Acc.id).Rating_Status__c) || Test.isRunningTest() ) 
  
  {
     CASE cas = new CASE(AccountID=acc.id);
     cas.subject = 'Rating';
     cas.origin =  'Rating Time'; 
     cas.Status = 'in Bearbeitung';
     cas.betreut_von__c = 'Max Mustermann';

     caToInsert.add(cas);
     
  }
  
}
}
    try{
      insert caToInsert; 

}
    catch(system.Dmlexception e){
    system.debug(e);

}
 
}


-----------------------------

@isTest

public class createCaseAfterAccountTest

{

    static testMethod void testMethod1()

    {

        Account testAccount = new Account();

        testAccount.Type='Kunde' ;

        testAccount.name='Demo';
        
        testAccount.billingpostalcode = '80000';
        
        testAccount.billingcountry = 'Deutschland';

        // add all required field

        insert testAccount;

         

        testAccount.name='Demo1';

        update testAccount;

    }

}
Sandra WicketSandra Wicket
OR operator can only be applied to Boolean expressions line 4 
Amit Chaudhary 8Amit Chaudhary 8
Please try below code

trigger createCaseafterAccountv2 on ACCOUNT(after update)
{
  List<CASE> caToInsert = new List<CASE>();
    for(ACCOUNT acc : Trigger.new  )
    {
        if(acc.Rating_Status__c == 'heute fällig' || Test.isRunningTest() )
        {
            if( ( acc.Rating_Status__C != Trigger.oldMap.get(Acc.id).Rating_Status__c) || Test.isRunningTest() )
            {
                 CASE cas = new CASE(AccountID=acc.id);
                 cas.subject = 'Rating';
                 cas.origin =  'Rating Time';
                 cas.Status = 'in Bearbeitung';
                 cas.betreut_von__c = 'Max Mustermann';

                 caToInsert.add(cas);
            
            }
      
        }
    }
    try{
      insert caToInsert;

    }
    catch(system.Dmlexception e){
        system.debug(e);
    }
 
}

Please let us know if this will help you
This was selected as the best answer
Sandra WicketSandra Wicket
Thanks Amit ! It works. I am a "developer" newbie and maybe it is a stupid question but why i have to add Test.isRunningTest () ? Is it for the test class ? to "communicate" with the trigger ?   And in my test class... why i dont have to test "insertCase "?  Sry but that was my first trigger and i want learn more ;)