I have an Account, with a related BillToAccount.

How do I create correctly the hierarchy in the test class?

Following code returns an error

FIELD_CUSTOM_VALIDATION_EXCEPTION, Bill To Account can not be empty: [Bill_To_Account__c]

There is a Validation Rule on that field, but it fires according to the type (the validation rule is ok - no need to check it)

the test method I have now is:

public static Account generateAccount(string m_Name)
    Account acc = new Account();
    acc.Name = m_Name;
    acc.type = 'Customer';
    acc.BillingCountry = 'Israel';

    if (acc.type == 'Customer')
        Account btacc = new Account();
        btacc.name = 'testbillto';
        btacc.type = 'Channel Partner / Dealer';
        btacc.BillingCountry = 'Israel';
        insert btacc;
        acc.Bill_To_Account__r = btacc;

    insert acc;
    return acc;

billingcountry and type are mandatory.

I want that: acc.Bill_To_Account - will get the test bill to account I create.

  • btacc is mandatory only if acc.type == 'Customer'

2 Answers 2


Instead of:

acc.Bill_To_Account__r = btacc;


acc.Bill_To_Account__c = btacc.Id;

The relationship has to be set via the Id value not the object reference.


Use try:

Boolean isDMLException = false;
 insert acc;
catch(DmlException ex){
    isDMLException = true;

System.assertEqual(true. isDMLException, 'Wrong exception result : ')

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .