function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Help Writing Test Class



I'm a novice in writing Apex classes, and copied some code I found on these boards. I need to write a test class to increase my code coverage and am incredibly unfamilliar with the language. Any help would be greatly appreciated.


public class ContactEntry {

    public List<Contact> con {get; set;}

    public ContactEntry(ApexPages.StandardController myController) {
        con = new List<Contact>();
        con.add(New Contact());}

    public void addrow() {
        con.add(new Contact());}
    public void removerow(){
        Integer i = con.size();
    public PageReference save() {
        insert con;
        //PageReference home = new PageReference('/home/home.jsp');
        //return home; }}
        PageReference conlist = new PageReference('/apex/contactlist');
        return conlist; }}

 Thank you in advance!

Hengky IlawanHengky Ilawan



There is a good article about unit test class here.


You may want to take a look at Salesforce own documentation:





Hi, as suggested the best place to start learning about test coverages would be salesforce documentation.


For now, you should atleast be aware why you need test coverage and how to do that!



To ensure that the code you've written is getting used, ie, it isn't unnecessary for your functionality.



You write apex to perform some operation/functionality, so write test coverage in such a way that your code has to behave the way it is expected to.




I have this small class


public class deleteAccount()


     public deleteAccount()



     public void deleteAcc(Id idToBeDeleted)


          Account a = [Select Id From Account Where Id = : idToBeDeleted];

          delete a;




Your class simply deletes an account based on it's id.


So you write your test coverage this way:


Account a = new Account(Name = 'test');

insert a; // you create a test record for your test class



private class testDeleteAccount


     private static void del()


          deleteAccount del = new deleteAccount();

          del.deleteAcc(a.Id); // now you are calling your class method, this is what you mean by code-coverage.




Btw, this code should help you for your class.



private class testContactEntry


     private static void testCE()


          Contact c = new Contact(LastName = 'test'); // add other required field, if any

          insert c;


          ApexPages.standardController std = new ApexPages.standardController(c);


          ContactEntry objCE = new ContactEntry(std);











NOTE : your Contact List con has contacts without LastNAme (a required field), so it will throw error on save.