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
Kunal Purohit 4Kunal Purohit 4 

How to write test class for given Apex class?

Hello, I am new to salesforce development. I want to write test class for given apex controller. Please help.

public without sharing class CreateNachaFileController {
	public String key;
	private ApexPages.StandardSetController standardController;
	public string headerImmediateDestination { get; set; }
	public string headerImmediateOrigin { get; set; }
	public string headerFileIdModifier { get; set; }
	public string headerDestinationName { get; set; }
	public string headerImmediateOriginName { get; set; }
	public string batchCompanyName { get; set; }
	public string batchCompanyId { get; set; }
	public string batchOriginatingDfiID { get; set; }
	public string batchCompanyEntryDescription { get; set; }
	public string batchCompanyDescriptiveDate { get; set; }
	public NachaFile nacha { get; set; }
	public Integer TotalCount { get; set; }
	public Decimal Total { get; set; }
	public String ServiceClass { get; set; }
	public Invoice_Header__c invoice { get; set; }
	public Customer_Payment__c NewPayment { get; set; }
	public List<SelectOption> nachaDefaultNames { get; set; }
	public String selectedNachaDefaultName { get; set; }
	public Boolean hasSplits { get; set; }
	private Map<String, CS_Nacha_Defaults__c> nachaDefaults;
	public Map<Id, InvoiceSplitWrapper> splitWrappers { get; set; }


	/////////////////////////////////////////////////////////////////
	// Outgoing (Vendor) NACHA
	/////////////////////////////////////////////////////////////////
	/**
	 * @description Constructor when called from Visualforce page as an extension, like CreateNachaFile
	 * @param standardController 
	 */
	public CreateNachaFileController(ApexPages.StandardSetController standardController) {
		if (this.standardController == null) {
			this.standardController = standardController;
			InitializeDefaults();
			headerFileIdModifier = 'A';
		}
	}

	public PageReference CreateNachaFile1() {
		return Page.CreateNachaFile;
	}

	public PageReference CreateNachaFile2() {
		TotalCount = 0;
		Decimal totalCalc = 0.0;
		Total = 0.0;
		Id[] ids = new List<Id> ();
		for (Vendor_Payment__c payment : (List<Vendor_Payment__c>) standardController.getSelected()) {
			ids.add(payment.Id);
			TotalCount++;
			if (payment.Total__c != null) { totalCalc = totalCalc + payment.Total__c; }
		}
		Total = totalCalc.setScale(2);

		nacha = new NachaFile();
		nacha.headerData.headerImmediateDestination = headerImmediateDestination.left(10);
		nacha.headerData.headerImmediateOrigin = headerImmediateOrigin.left(10);
		nacha.headerData.headerFileIdModifier = headerFileIdModifier.left(1);
		nacha.headerData.headerDestinationName = headerDestinationName.left(23);
		nacha.headerData.headerImmediateOriginName = headerImmediateOriginName.left(23);

		nacha.headerData.batchCompanyEntryDescription = batchCompanyEntryDescription == null ? '' : batchCompanyEntryDescription.left(10);
		nacha.headerData.batchCompanyName = batchCompanyName.left(16);
		nacha.headerData.batchCompanyId = batchCompanyId.left(10);
		nacha.headerData.batchOriginatingDfiID = batchOriginatingDfiID.left(8);

		nacha.headerData.serviceClass = ServiceClass;

		nacha.generateFile(ids);

		return Page.CreateNachaFile2;
	}

	public PageReference CreateNachaFile3() {
		// Create Nacha_File__c record
		NACHA_File__c nf = new NACHA_File__c();
		nf.Destination_Name__c = nacha.headerData.headerDestinationName;
		nf.File_Id_Modifier__c = nacha.headerData.headerFileIdModifier;
		nf.Generated_By__c = UserInfo.getUserId();
		nf.Immediate_Destination__c = nacha.headerData.headerImmediateDestination;
		nf.Immediate_Origin__c = nacha.headerData.headerImmediateOrigin;
		nf.Immediate_Origin_Name__c = nacha.headerData.headerImmediateOriginName;
		nf.Service_Class__c = nacha.headerData.serviceClass;
		insert nf;
		List<Vendor_Payment__c> payment = (List<Vendor_Payment__c>) standardController.getSelected();
		for (Vendor_Payment__c detail : payment) {
			detail.Status__c = 'Payment Sent';
			detail.Date_Paid__c = Date.today();
			detail.NACHA_File__c = nf.Id;
		}
		standardController.save();
		return Page.CreateNachaFile3;
	}

	public PageReference cancel() {
		Schema.DescribeSObjectResult anySObjectSchema = Vendor_Payment__c.SObjectType.getDescribe();
		String objectIdPrefix = anySObjectSchema.getKeyPrefix();
		PageReference pageReference = new PageReference('/' + objectIdPrefix + '/o');
		pageReference.setRedirect(true);
		return pageReference;
	}

	/////////////////////////////////////////////////////////////////
	// Incoming (Customer) NACHA
	/////////////////////////////////////////////////////////////////
	/**
	 * @description Constructor when called from Visualforce page as Controller - CreateIncomingNachaFile.page
	 */
	public CreateNachaFileController() {
		InitializeDefaults();
		headerFileIdModifier = 'H';
		batchCompanyEntryDescription = 'RECEIVABLE';
		batchCompanyDescriptiveDate = string.valueof(DateTime.now().month()) + string.valueof(DateTime.now().year()).substring(2, 4);

		invoice = [SELECT
		           Id, Name, Customer_Id__c, Customer_Name__c, Invoice_Total__c, Total_Balance__c, Document_Date__c, Memo__c,
		           Customer_ID__r.Bank_Account__c, Customer_ID__r.Bank_Routing__c, Customer_Id__r.Receivables_Account_Id__c, Customer_ID__r.NACHA_Vendor_NameFx__c
		           , (select Id, Name, Invoice_Split_Amount__c, Bank_Information__r.Name, Bank_Information__r.Bank_Account__c, Bank_Information__r.Bank_Routing__c, Exclude_from_NACHA_Files__c from Invoice_Splits__r)
		           FROM Invoice_Header__c
		           where Id = :key];

		hasSplits = invoice.Invoice_Splits__r.size() > 0;

		NewPayment = new Customer_Payment__c();
		NewPayment.Customer_Id__c = invoice.Customer_Id__c;
		NewPayment.Tran_Date__c = Date.today() + 1;
		NewPayment.Default_Vendor_Payment_Date__c = PaymentFromCustomerController.calculateNthWorkingDay(Date.today() + 1, 1);
		NewPayment.AR_Account_Id__c = invoice.Customer_Id__r.Receivables_Account_Id__c;
		NewPayment.Payment_Type__c = 'ACH';

		NewPayment.Amount__c = invoice.Total_Balance__c;
		System.debug(hasSplits);
		if (hasSplits) {
			NewPayment.Amount__c = 0;
			splitWrappers = new Map<Id, InvoiceSplitWrapper> ();
			for (Invoice_Split__c split : invoice.Invoice_Splits__r) {
				System.debug(split);
				System.debug(split.Exclude_from_NACHA_Files__c);
				if (split.Exclude_from_NACHA_Files__c == false) {
					System.debug('included');
					InvoiceSplitWrapper splitWrapper = new InvoiceSplitWrapper(split);
					splitWrapper.checked = true;
					splitWrappers.put(splitWrapper.invoiceSplit.Id, splitWrapper);
					NewPayment.Amount__c += split.Invoice_Split_Amount__c;
					System.debug(NewPayment.Amount__c);
				}
			}
		}
		System.debug(splitWrappers);

	}
	public PageReference CreateIncomingNachaFile1() {
		return Page.CreateIncomingNachaFile;
	}

	public PageReference CreateIncomingNachaFile2() {
		if (NewPayment.Amount__c == null || NewPayment.Tran_Date__c == null) {
			ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO, 'Amount and Payment Date are required before saving.');
			ApexPages.addMessage(myMsg);
			return null;
		}
		if (hasSplits) {
			NewPayment.Amount__c = 0;
			for (Id key : splitWrappers.keySet()) {
				InvoiceSplitWrapper sw = splitWrappers.get(key);
				if (sw.checked) {
					NewPayment.Amount__c += sw.invoiceSplit.Invoice_Split_Amount__c;
				}
			}
		}
		TotalCount = 0;
		Decimal totalCalc = 0.0;
		Total = 0.0;
		TotalCount = 1;
		totalCalc = NewPayment.Amount__c; //invoice.Total_Balance__c;
		Total = totalCalc.setScale(2);

		nacha = new NachaFile();
		nacha.headerData.headerImmediateDestination = headerImmediateDestination.left(10);
		nacha.headerData.headerImmediateOrigin = headerImmediateOrigin.left(10);
		nacha.headerData.headerFileIdModifier = headerFileIdModifier.left(1);
		nacha.headerData.headerDestinationName = headerDestinationName.left(23);
		nacha.headerData.headerImmediateOriginName = headerImmediateOriginName.left(23);

		nacha.headerData.batchCompanyName = batchCompanyName.left(16);
		nacha.headerData.batchCompanyId = batchCompanyId.left(10);
		nacha.headerData.batchOriginatingDfiID = batchOriginatingDfiID.left(8);
		nacha.headerData.batchCompanyEntryDescription = batchCompanyEntryDescription.left(10);
		nacha.headerData.batchCompanyDescriptiveDate = batchCompanyDescriptiveDate.left(6);

		nacha.headerData.serviceClass = ServiceClass;
		nacha.AmountOverride = NewPayment.Amount__c;
		nacha.PaymentDate = NewPayment.Tran_Date__c;
		System.debug(nacha);
		System.debug(splitWrappers);
		nacha.generateIncomingFile(new List<Invoice_Header__c> { invoice }, splitWrappers);

		return Page.CreateIncomingNachaFile2;
	}

	public PageReference CreateIncomingNachaFile3() {
		//Save New Payment, then save nacha file
		if (!CreateNewPayment()) return null;
		return Page.CreateIncomingNachaFile3;
	}

	// Incoming (Customer) NACHA
	public void actionSupportChangePmtDivision() {
		Id glAccount = null;
		Id pmtDivisionId = NewPayment.Payment_Division_Id__c;
		List<Payment_Division__c> pmtDivisions = [SELECT Id, Name, GL_Account_Id__c FROM Payment_Division__c WHERE Id = :pmtDivisionId];
		NewPayment.GL_Account_Id__c = null;
		if (pmtDivisions.size() != 0) {
			for (Payment_Division__c pd : pmtDivisions) {
				NewPayment.GL_Account_Id__c = pd.GL_Account_Id__c;
			}
		}
	}
	// Incoming (Customer) NACHA
	public boolean CreateNewPayment() {
		// Create Nacha_File__c record
		NACHA_File__c nf = new NACHA_File__c();
		//nacha.Name = 
		nf.Destination_Name__c = nacha.headerData.headerDestinationName;
		nf.File_Id_Modifier__c = nacha.headerData.headerFileIdModifier;
		nf.Generated_By__c = UserInfo.getUserId();
		nf.Immediate_Destination__c = nacha.headerData.headerImmediateDestination;
		nf.Immediate_Origin__c = nacha.headerData.headerImmediateOrigin;
		nf.Immediate_Origin_Name__c = nacha.headerData.headerImmediateOriginName;
		nf.Service_Class__c = nacha.headerData.serviceClass;
		insert nf;

		if (!hasSplits) {
			if (NewPayment.Amount__c == null || NewPayment.Tran_Date__c == null) {
				ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO, 'Amount and Payment Date are required before saving.');
				ApexPages.addMessage(myMsg);
				return false;
			}

			decimal totalAmountApplied = NewPayment.Amount__c;
			NewPayment.NACHA_File__c = nf.Id;
			insert NewPayment;
			Customer_Payment_Apply__c application = new Customer_Payment_Apply__c();
			application.Customer_Payment_Id__c = NewPayment.Id;
			application.Invoice_Id__c = invoice.Id;
			application.Amount__c = NewPayment.Amount__c;
			insert application;
			return true;
		} else {
			if (NewPayment.Tran_Date__c == null) {
				ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO, 'Payment Date is required before saving.');
				ApexPages.addMessage(myMsg);
				return false;
			}
			Customer_Payment__c[] paymentsToInsert = new List<Customer_Payment__c> ();
			Customer_Payment_Apply__c[] applicationsToInsert = new List<Customer_Payment_Apply__c> ();

			for (Invoice_Split__c split : invoice.Invoice_Splits__r) {
				system.debug(split);
				Customer_Payment__c splitPayment = new Customer_Payment__c();
				splitPayment.NACHA_File__c = nf.Id;
				splitPayment.Amount__c = split.Invoice_Split_Amount__c;
				splitPayment.Customer_Id__c = NewPayment.Customer_Id__c;
				splitPayment.Tran_Date__c = NewPayment.Tran_Date__c;
				splitPayment.Default_Vendor_Payment_Date__c = NewPayment.Default_Vendor_Payment_Date__c;
				splitPayment.AR_Account_Id__c = NewPayment.AR_Account_Id__c;
				splitPayment.Payment_Type__c = NewPayment.Payment_Type__c;
				splitPayment.GL_Account_Id__c = NewPayment.GL_Account_Id__c;
				splitPayment.Payment_Division_Id__c = NewPayment.Payment_Division_Id__c;
				splitPayment.Coverage_Month__c = NewPayment.Coverage_Month__c;
				splitPayment.Location__c = NewPayment.Location__c;
				splitPayment.Memo__c = NewPayment.Memo__c;
				splitPayment.Posting_Period__c = NewPayment.Posting_Period__c;
				splitPayment.Batch__c = NewPayment.Batch__c;
				splitPayment.COL_Code__c = NewPayment.COL_Code__c;
				paymentsToInsert.add(splitPayment);

			}
			insert paymentsToInsert;
			for (Customer_Payment__c pmt : paymentsToInsert) {
				Customer_Payment_Apply__c application = new Customer_Payment_Apply__c();
				application.Customer_Payment_Id__c = pmt.Id;
				application.Invoice_Id__c = invoice.Id;
				application.Amount__c = pmt.Amount__c;
				applicationsToInsert.add(application);

			}
			insert applicationsToInsert;
			return true;
		}
	}

	// Incoming NACHA
	public PageReference cancelToInvoice() {
		PageReference pageReference = new PageReference('/' + key);
		pageReference.setRedirect(true);
		return pageReference;
	}


	/////////////////////////////////////////////////////////////////
	// Both Regular NACHA and Incoming NACHA
	/////////////////////////////////////////////////////////////////
	private void InitializeDefaults() {
		key = ApexPages.currentPage().getParameters().get('invoiceid');

		nachaDefaultNames = new List<SelectOption> ();
		nachaDefaults = new Map<String, CS_Nacha_Defaults__c> ();

		// Need to order by Ordinal__c so I went with the direct SOQL route instead of the cached call (getAll)
		for (CS_Nacha_Defaults__c nd :[SELECT Name, Immediate_Origin__c, Immediate_Origin_Name__c, Immediate_Destination__c, Destination_Name__c,
		     Company_Name__c, Company_Id__c, Originating_DFI_Id__c, Company_Entry_Description__c
		     FROM CS_Nacha_Defaults__c
		     WHERE Active__c = true
		     ORDER BY Ordinal__c DESC]) {
			nachaDefaultNames.add(new SelectOption(nd.Name, nd.Name));
			nachaDefaults.put(nd.Name, nd);
		}

		selectedNachaDefaultName = nachaDefaultNames[0].getValue();
		setDefaults();

	}


	public void setDefaults() {

		CS_Nacha_Defaults__c selectedNachaDefault = nachaDefaults.get(selectedNachaDefaultName);
		//headerImmediateDestination = '011900254'; 
		//headerImmediateOrigin = '1200645984'; 
		//headerDestinationName = 'BANK OF AMERICA'; 
		//headerImmediateOriginName = 'PLANSOURCE BEN ADMIN'; 
		//batchCompanyName = 'PLANSOURCE'; 
		//batchCompanyId = '1550800751'; 
		//batchOriginatingDfiID = '011900254'; 
		headerImmediateDestination = selectedNachaDefault.Immediate_Destination__c;
		headerImmediateOrigin = selectedNachaDefault.Immediate_Origin__c;
		headerDestinationName = selectedNachaDefault.Destination_Name__c;
		headerImmediateOriginName = selectedNachaDefault.Immediate_Origin_Name__c;
		batchCompanyName = selectedNachaDefault.Company_Name__c;
		batchCompanyId = selectedNachaDefault.Company_Id__c;
		batchOriginatingDfiID = selectedNachaDefault.Originating_DFI_Id__c;
		batchCompanyEntryDescription = selectedNachaDefault.Company_Entry_Description__c;
	}

}
Best Answer chosen by Kunal Purohit 4
SwethaSwetha (Salesforce Developers) 
HI Kunal,
Since this code provided is huge and requires an understanding of your implementation, it might not be possible to provide exact test class suggestions. However, the below information should help you get started.

The below articles give a good insight into how to begin writing test class and how coverage can be improved

https://salesforce.stackexchange.com/questions/244788/how-do-i-write-an-apex-unit-test
https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines 

Examples:
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm
 https://salesforce.stackexchange.com/questions/87533/writing-test-class-for-wrapper-class
https://salesforce.stackexchange.com/questions/108850/apex-test-method-for-wrapper-classes

If this information helps, please mark the answer as best. Thank you