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
sai harishsai harish 

Please help me in writing this Test Class which is used in Lightning Component to update a Record

Please help me write Test class. I am using this class in a Lightning component to update a Record in a detail page. I am new to salesforce and unable to figure out how to write test class and get my class covered. Thanks in advance.

Apex Class:
public class ApproveAP {
    @AuraEnabled
    public static String updatepayable(String payId) {
        String msg = 'Approved';
        try {
            update new AcctSeed__Account_Payable__c(id = payId, AcctSeed__Status__c = 'Approved');
        }
        catch(Exception e) {
            msg = e.getMessage();
        }
        return msg;
    }
}
Test Class : 
@isTest
private class TestApproveAP
   {
 private static Testmethod string updatepayable(){
   string msg = 'Test Message';
      List<AcctSeed__Account_Payable__c> accList = new List<AcctSeed__Account_Payable__c>();
      accList.add(
      new AcctSeed__Account_Payable__c(
       id='tempId',
      AcctSeed__Status__c = 'Waiting for Approval'
      )
      );
      insert accList;
  
  try{
  update new AcctSeed__Account_Payable__c(id = 'tempId', AcctSeed__Status__c = 'Approved');
  }catch(Exception e){msg=e.getMessage();
   ApproveAP app = new ApproveAP();
   }
  return msg;
 }
 }
Best Answer chosen by sai harish
jigarshahjigarshah
Modify your ApproveAP class as follows.
public class ApproveAP {

	@TestVisible private static String msg = 'Approved';

    @AuraEnabled
    public static String updatepayable(String payId) {
        
        try {
            update new AcctSeed__Account_Payable__c(id = payId, AcctSeed__Status__c = 'Approved');
        }
        catch(Exception e) {
            msg = e.getMessage();
        }
        return msg;
    }
}

Here is the test code for ApproveAP that should provide adequate code coverage.
@isTest(SeeAllData = false)
public class ApproveAPTest {

    private String accountPayableErrorMsg = '';
	
    static testMethod void checkAccountPayableApproval(){
		
		//Create a new AcctSeed__Account_Payable__c record
		Database.SaveResult accountPayableSaveResult = 
			Database.insert(
				new AcctSeed__Account_Payable__c(
					Name = 'Test Account Payable', 
					AcctSeed__Status__c = 'Waiting for Approval'));
			
		test.startTest();
		
		//Invoke the Aura Method and pass the AcctSeed__Account_Payable__c record Id to update
		accountPayableErrorMsg = ApproveAP.updatepayable(accountPayableSaveResult.getId());
				
		test.stopTest();
		
        //Assert if the proper error message string was returned
        System.assertEquals(accountPayableErrorMsg, 'Approved', 'Msg is approved');

		//Retrieve the update Accoutn Payable record
		List<AcctSeed__Account_Payable__c> updatedAccountPayable = 
			[Select Id, Name, AcctSeed__Status__c 
			 From AcctSeed__Account_Payable__c 
			 Where Id = :accountPayableSaveResult.getId()];

		//Assert if the Accounts Payable record in consideration was approved or not
		System.assertEquals(
			updatedAccountPayable, 'Approved', 'Payable record approved.');
	}
}
Please mark this thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.

All Answers

jigarshahjigarshah
Modify your ApproveAP class as follows.
public class ApproveAP {

	@TestVisible private static String msg = 'Approved';

    @AuraEnabled
    public static String updatepayable(String payId) {
        
        try {
            update new AcctSeed__Account_Payable__c(id = payId, AcctSeed__Status__c = 'Approved');
        }
        catch(Exception e) {
            msg = e.getMessage();
        }
        return msg;
    }
}

Here is the test code for ApproveAP that should provide adequate code coverage.
@isTest(SeeAllData = false)
public class ApproveAPTest {

    private String accountPayableErrorMsg = '';
	
    static testMethod void checkAccountPayableApproval(){
		
		//Create a new AcctSeed__Account_Payable__c record
		Database.SaveResult accountPayableSaveResult = 
			Database.insert(
				new AcctSeed__Account_Payable__c(
					Name = 'Test Account Payable', 
					AcctSeed__Status__c = 'Waiting for Approval'));
			
		test.startTest();
		
		//Invoke the Aura Method and pass the AcctSeed__Account_Payable__c record Id to update
		accountPayableErrorMsg = ApproveAP.updatepayable(accountPayableSaveResult.getId());
				
		test.stopTest();
		
        //Assert if the proper error message string was returned
        System.assertEquals(accountPayableErrorMsg, 'Approved', 'Msg is approved');

		//Retrieve the update Accoutn Payable record
		List<AcctSeed__Account_Payable__c> updatedAccountPayable = 
			[Select Id, Name, AcctSeed__Status__c 
			 From AcctSeed__Account_Payable__c 
			 Where Id = :accountPayableSaveResult.getId()];

		//Assert if the Accounts Payable record in consideration was approved or not
		System.assertEquals(
			updatedAccountPayable, 'Approved', 'Payable record approved.');
	}
}
Please mark this thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.
This was selected as the best answer
sai harishsai harish
Hi Jigarshah,

Thank you for the response. I am getting an error when trying to use the code you provided. I am attaching a screenshot so that you can see the error. I also forgot to mention that the Name field is an auto number. I tried to remove the name field and save it but it is giving me this error.User-added image

I really appreciate your efforts in trying to help me.

Thanks.
Sai Harish.
jigarshahjigarshah
Mark the accountPayableErrorMsg as static as below in line # 4 of your test class.
 
static String accountPayableErrorMsg = '';

 
sai harishsai harish
Hi Jigarshah,

I updated the code you as told. I could save the test class but when 1 run it, my method does not pass and I am getting this error. 

User-added image

Thanks once again jigarshah.
jigarshahjigarshah
The insert operation is failing. Check the Debug Log to identify the reason for the failure of the insert operation. This could be becuase oyu may not have have included the required fields with values for AcctSeed__Account_Payable__c while inserting the record.
sai harishsai harish
Hi Jigarshah,
The Name field in this object is an autonumber. So, I had to take off the Name field otherwise I am getting this error  Compile Error: Field is not writeable: AcctSeed__Account_Payable__c.Name at line 11 column 17. 

User-added image
jigarshahjigarshah
The error is because the Issue Date is being set to a past Date which is invalid, while the Accounts Payable record is inserted. This is because of a custom Validation Rule on Accounts Payable object.

Ensure the date value is being set appropriately which complies with the validaiton rule mandates. If you deactivate the validation rule and run the test code you will get the coverage but use this as a mechanism for testing only.
sai harishsai harish
Hi Jigarshah,

I went to the validation rules and deactivated all the date related validation rules but that did not do it. Then I added the issue date field in the code.  

 Database.SaveResult accountPayableSaveResult = 
            Database.insert(
                new AcctSeed__Account_Payable__c(
                 AcctSeed__Date__c = Date.today(),
                 AcctSeed__Status__c = 'Waiting for Approval'));
            
        test.startTest();
        
        //Invoke the Aura Method and pass the AcctSeed__Account_Payable__c record Id to update
        accountPayableErrorMsg = ApproveAP.updatepayable(accountPayableSaveResult.getId());
                
        test.stopTest();
        
        //Assert if the proper error message string was returned
        System.assertEquals(accountPayableErrorMsg, 'Approved', 'Msg is approved');

        //Retrieve the update Accoutn Payable record
        List<AcctSeed__Account_Payable__c> updatedAccountPayable = 
            [Select Id, AcctSeed__Status__c, AcctSeed__Date__c  
             From AcctSeed__Account_Payable__c 
             Where Id = :accountPayableSaveResult.getId()];

        //Assert if the Accounts Payable record in consideration was approved or not
        System.assertEquals(
            accountPayableErrorMsg, 'Approved', 'Payable record approved.');
    }
}

I am still getting the same validation error. Any suggestions from you are appreciated.

Thanks.
Sai Harish.
jigarshahjigarshah
Date doesn't seem correct. Copy the date value from one of the records which has been approved. This should help you work past the issue.
sai harishsai harish
Hi Jigarshah,

I tried using 2 or 3 dates from records that are already approved and tried to run my test class. It is still giving me the same error. I am giving the date as follows. 

  new AcctSeed__Account_Payable__c(
                 AcctSeed__Date__c = Date.newInstance(2017, 24, 10),
                 AcctSeed__Status__c = 'Waiting for Approval'));
This AcctSeed__Date__c  field is from a managed package. It is a Required field and default value is Today().
 
jigarshahjigarshah
I can have a look at your org and advise. Please share the credentials of your org where the code exists.
sai harishsai harish
Hi Jigar shah,

Sorry for the delayed response. I used the below code to get 100% code coverage. I had to define a accounting period and give two date instances for start date and end date. I really appreciate your efforts to help me.

@isTest

private class TestApproveAP{
   static testMethod void updatepayable(){
    List<AcctSeed__Accounting_Period__c> accp = new List<AcctSeed__Accounting_Period__c>();
     accp.add(
     new AcctSeed__Accounting_Period__c(
     Name='2017-12',
     AcctSeed__Start_Date__c = Date.newInstance(2017,12,1) ,
     AcctSeed__End_Date__c = Date.newInstance(2017,12,31)
     
     )
     );
     insert accp;
    List<AcctSeed__Account_Payable__c> payable = new List<AcctSeed__Account_Payable__c>();
     payable.add(
     new AcctSeed__Account_Payable__c(
     AcctSeed__Payee_Reference__c = 'Test Payee',
     AcctSeed__Contact__c = '003d000000QCmQB',  
     AcctSeed__Status__c = 'Waiting for Approval',
     AcctSeed__Date__c = Date.newInstance(2017,12,7),
     AcctSeed__Accounting_Period__c = 'a3g0V000001UL17'
     )
     );
     insert payable;
     ApproveAP.updatePayable(payable[0].id);
   }
}
jigarshahjigarshah
Sai Harish,

Great that you were able to get your test code working. If the answers have helped you, please marked this thread as SOLVED and the answer that bets helped you as the BEST ANSWER.