Firstly, the code which you mentioned as test class
is not really a test class. The syntax for test class is something like below i.e. it should have an annotation @isTest
which says that, this particular code is only testing the functionality and not really changing anything in the database. You can go through salesforce trailhead moudle Apex Testing to learn how to write test classes.
@isTest
private class MyTestClass {
@isTest static void myTest() {
// code_block
}
}
Now coming to your test class which actually is not, there are few things you need to correct
- You have some syntactical errors in your code which is the reason the code is not getting compiled i.e. you are missing a closing brace (I hope it is just a typo).
- I am not sure how your code executed successfully as it should have given you error
cannot specify Id in an insert call
at insert obj;
line as you cannot and should not specify the Id
in a insert call.
- You should not use hard-coded
Id
values as data won't be accessible to the code in test class as on Salesforce, all unit tests are executed in an isolated context. So your code in test class cannot see data in your organization. Although there is an annotation called seeAllData=true
which allows tests to see all data in the Salesforce but this is strictly not recommended.
You can go though this canonical question developed by SFSE community How do I write an Apex unit test? which will help you understand and learn these concepts.
As far as your test class is concerned, you should make sure that you create the test data as input for your code, which ensures that all the logical paths are executed.
So your code for test class should be
@isTest
private class Correction_CounterTestClass {
@isTest static void myTest_CounterZero(){
Case obj = new Case();
obj.Status = 'Open'; //Set this to any other valid status other than 'Correction Requested' as you are checking for status change in your trigger
obj.Correction_Counters__c = 0;
insert obj;
Test.startTest();
obj.Status = 'Correction Requested';
update obj;
Test.stopTest();
System.assertEquals(0.1, obj.Correction_Counters__c);
}
@isTest static void myTest_CounterNonZero(){
Case obj = new Case();
obj.Status = 'Open'; //Set this to any other valid status other than 'Correction Requested' as you are checking for status change in your trigger
obj.Correction_Counters__c = 2;
insert obj;
Test.startTest();
obj.Status = 'Correction Requested';
update obj;
Test.stopTest();
System.assertEquals(2.5, obj.Correction_Counters__c);
}
}
Note : Your trigger is not bulkified and hence it will work only for single record. As a best practice, it is always recommended to bulkify your code. You can refer Apex Triggers trailhead module to learn on this topic.