I have an Inbound Email Handler that automatically creates a Lead and converts it. The Record Type for the corresponding Account is correctly set to the default Account Record Type that is configured in the used User Profile - in this case, it is created as a Person Account.

When I'm doing the same thing in a unit test it instead uses the Account Record Type, even though I'm using runAs() with a User that has the same User Profile set.

Why does this happen? Is there a way to test this?

A few months ago I already posted a very similar question: How can I set the Account Record Type for Lead conversion?

Now the odd behavior that I experienced there became a real problem as it totally screws my tests and makes it impossible to know if I have introduced any regressions.

public with sharing class HandleEmailsHelper {
    public static void checkEmail(Messaging.InboundEmail email) {
        Lead ld = new Lead();
        ld.RecordTypeId = Utils.getRecordTypeId('Lead', 'Customer');
        insert ld;

trigger LeadTrigger on Lead (before insert, before update, before delete, after insert, after update, after delete) {
    if (Trigger.isBefore && Trigger.isInsert) {

public with sharing class LeadHelper {
    public static void autoConvertCustomerLeads(Map<Id, Lead> leadMap) {
        List<Database.LeadConvert> leadCvtList = new List<Database.LeadConvert>();

        for (Lead ld : emailLeadMap.values()) {
            leadCvtList.add(setupLeadConvert(ld, null, convertStatus));

        List<Database.LeadConvertResult> lcr = Database.convertLead(leadCvtList);

    private static Database.LeadConvert setupLeadConvert(Lead ld, Id acctId, LeadStatus convertStatus) {
        Database.LeadConvert lc = new Database.LeadConvert();


        if (acctId != null) {

        return lc;
  • 3
    Could you possibly share a minimal example of a unit test that causes this issue? I don't personally know the answer to this question but I think it's interesting and would love to experiment in a developer edition.
    – David Reed
    Dec 21, 2018 at 2:16
  • I will take it from production and strip out all the fluff and hope it will still behave the same way.
    – Semmel
    Dec 21, 2018 at 10:06
  • I added the code minus all the fluff - but it is still missing the actual test. I will add it later.
    – Semmel
    Dec 21, 2018 at 14:30


You must log in to answer this question.

Browse other questions tagged .