[SalesForce] Apex Unit Tests – Approach!

Hello Folks,

I think all of my questions cover the approach more than the technical detail or aspect. Here is another one, this one relates to force.com unit tests!**

I know there have been significant improvements in the API v24.0 and greater regarding the unit tests but this might be a really simple use case which might help a lot of other people!

Class:

Public class DeleteRecords{
    Public void DeleteAllRecords(){
           List <sObject> ListSobject = [Select Id from sObject limit 9000];
           //DML on the List - Example Delete
           Delete listsObject;
    }
}

Test Class:

@isTest(SeeAllData=true)
    public class TestDeleteClass {    
           static testmethod void testDelete() {

            /*Approach 1 */
                 //Testing Delete
                 sObject abc = new sObject(RequiredField = 'test');
                 insert abc;
                 delete abc;

                 OR
           /*Approach 2 */
                 //Create an instance of the class and call the method
                 DeleteRecords dr = new DeleteRecord();
                 dr.DeleteAllRecords();

           }
    }

Please find the approach 1 and approach 2 both in the test class. The question is below:
At times, approach would not give me code coverage, I do not know why?! Yes, the records are present in my org. But approach 2 gives me 100% code coverage. Does it really mean my code is covered?!

I also want to know if its performing the delete test, how can I know if the test records are getting deleted?

Thank you!

Best Answer

The way to test this would be as follows. Note that SeeAllData is set to false as we are inserting the records in the testmethod.

@isTest(SeeAllData=false)
public class TestDeleteClass {    
       static testmethod void testDelete() {

             sObject abc = new sObject(RequiredField = 'test');
             insert abc;

             DeleteRecords dr = new DeleteRecord();

             Test.startTest();
             dr.DeleteAllRecords();
             Test.stopTest();

             system.assert([select ID from myobject__c].IsEmpty());
       }
}

Code coverage simply means that the lines of code were executed by your test method. It doesn't mean that your code is working correctly, you have to write asserts to verify that.

Related Topic