1

I'm Kinda newbie in APEX and Testing classes in general.


If I have this type of classes, which basicly about querying and retrieving data from database using SOQL statments:

public class classToTest{
    Public List<Account> attrNum1{get;set;}
    Public List<Opportunity> attrNum2{get;set;}
    public classToTest(){
        attrNum1 = [SELECT Id, Name FROM Account WHERE .... ];
        attrNum2 = [SELECT Id FROM Opportunity WHERE .... ];
    }
}

Is it right and acceptable if the test class is like this:

public class testingClass{
    static testMethod void testingClass(){
        Test.startTest();
        classToTest instanceNum1 = new classToTest();
        Test.stopTest();

        Set<Id> expectedRecordIds_attrNum1 = new Map<Id, SObject>([SELECT Id, Name FROM Account WHERE .... ]);
        Set<Id> actualIds_attrNum1 = new Map<Id, SObject>(instanceNum1.attrNum1);
        system.assertEquals(expectedRecordIds_attrNum1, actualIds_attrNum1);

        Set<Id> expectedRecordIds_attrNum2 = new Map<Id, SObject>([SELECT Id, Name FROM Account WHERE .... ]);
        Set<Id> actualIds_attrNum2 = new Map<Id, SObject>(instanceNum1.attrNum1);
        system.assertEquals(expectedRecordIds_attrNum2, actualIds_attrNum2);
    }
}

Or I have to insert record with the specific criteria of the SOQL statment in the classToTest and try to compare it with new instance's attributes.

Generally what happens because of the first three lines, in the test class, is a code coverage 100%, with that I noticed this number is not that important with this kind of classes. :\

  • In test class you test the functionality of the class/output of methods. Test data is created as input and using system.assert you check the output. So it all depends on the functionality of the method. – C0DEPirate Jul 6 '16 at 11:17
2

Yes, Create your own data inside a test class and then invoke a class methods.

In case of above example. 1. You need to create Account and Opportunity data 2. Invoke a constructor 3. You can assert statement to check if those many records are retrieve by your query. If the condition matched with the SOQL then query will return at least one record. You can verify this using System.assert statement.

You can write Test.startTest() after creating a test data. For example.

// the sample code could be,

//insert accountList

// insert opportunityList

// Now invoke a Test.startTest() to perform your testing

// Create instance of constructor and invoke class methods

// Test.stopTest()

// Write assert statement to verify results

Check below links regarding Apex Test Class,

How to write a unit-test / test class for trigger?

An Introduction to Apex Code Test Methods

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.