[SalesForce] How to create Case with Person Account in test class

@isTest
public class TestDataFactory {

    public static List<Account> createPersonAccount(Integer numOfAccounts){
        Id prsnAccountRecTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('PersonAccount').getRecordTypeId();
        List<Account> accountList = new List<Account>();

        for(Integer i = 0; i < numOfAccounts; i++){
            accountList.add(new Account(RecordTypeId= prsnAccountRecTypeId,
                                        FirstName= 'Test FN-' + i,
                                        LastName='Test LN-' + i,
                                        PersonEmail= 'test-' + i + '@example.com'));
        }

        insert accountList;
        return accountList;
    }

    public static List<Case> createCase(Integer numOfCases, List<Account> accounts){
        Id caseRecTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('KM_Case').getRecordTypeId();
        List<Case> caseList = new List<Case>();

        for(Integer i = 0; i < numOfCases; i++){

            caseList.add(new Case(Origin= 'Email',
                                  Status= 'New',
                                  Type= 'Credit/refund',
                                  Subject= 'Test Case Subject-' + i,
                                  Description= 'Test Case Description-' + i,
                                  KM_Case_Notes__c= 'Test Case Notes-' + i,
                                  Reason= 'New problem',
                                  ContactId= accounts[i].Id,
                                  AccountId= accounts[i].Id));
        }

        insert caseList;
        return caseList;
    }
}

Below error is returned when I try executing this test class.
Contact ID: id value of incorrect type: 0018A00000Toq4GQAR: [ContactId]
It works, if I remove the ContactId reference.
Please help, how can I create Case with PersonAccount linked as Account & Contact?

Best Answer

You need to query the PersonContactId field and use that instead. 001 is always an Account Id, while 003 is always a Contact Id.

    return accountList;

Should be more like:

return [SELECT FirstName, LastName, PersonContactId, PersonEmail FROM Account WHERE Id = :accountList];

Then you can:

ContactId= accounts[i].PersonContactId,
Related Topic