1

Here is my apex class with validation rule to populate one of the two custom fields, and not allowing to populate both custom fields at the same time:

public with sharing class FieldnotEmptycontrl {
    public static void fieldNotEmpty(List<Property__c> prop){
        for(Property__c property: prop){
            //if both fields are empty the error message shows up
            if(property.Business__c == null && property.Contact__c == null) {

                property.Business__c.addError('You must enter a value!');
                property.Contact__c.addError('You must enter a value!');
            }
                //if both fields are not empty the error message shows up
            if(property.Business__c != null && property.Contact__c != null){

                 property.Business__c.addError('Cannot use two fields at the same time. Please choose only one field Business or Contact');
                 property.Contact__c.addError('Cannot use two fields at the same time. Please choose only one field Business or Contact');
                }
            }
        }
    }

TEST class that needs to be finished to get 100% coverage:

@IsTest
private class FieldNotEmptyTest {
    @IsTest static void fieldNotEmptyTest() {

        Property__c prp = new Property__c();
        prp.Name = 'MyPropertyTest';
        prp.Business__c = 'Abc';
        prp.Contact__c = null;
        insert prp;

        List<Property__c> properties = new List<Property__c>();
        FieldnotEmptycontrl.fieldNotEmpty(properties);


        System.debug('Property field for Business is ' + prp.Business__c);
        System.assertEquals('Abc', prp.Business__c);

    }
}
1

You need to create 2 test methods:

  1. this will cover the first IF condition:

    prp.Business__c = null;
    prp.Contact__c = null;
    
  2. having the values in 2 fields, which will cover the second IF condition:

    prp.Business__c = 'Abc';
    prp.Contact__c = some_value; //based on the type you might need to create a test record of Contact if the field is lookup type;


1
  • 1
    Thank you, Aditya Vijay, for the hint! – Asel Vazirova Mar 24 '20 at 19:46

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.