1

I need to create an Apex test class for a Lead Apex Trigger that handles "before insert" of the web-to-lead inserts of Lead records that DON'T have OwnerId at the "before insert" time. Assigning of OwnerId is hadnled by the trigger.

How can I create a test class method that simulates this by inserting Leads with OwnerId = null?

1

You can't create a Lead with a null OwnerId, through Web-to-Lead, or in Apex. Lead.OwnerId is defaultedOnCreate, and so will be set when the object is created, before any triggers are run.

Unless set through a hidden form field (which is a bad idea anyway, as you'd be putting a User Id in public web forms), Lead.OwnerId will be set to the Default Lead Creator specified in Web-to-Lead settings. You could set that to a user that should never own Leads, and then base your trigger logic on that user owning the Lead. Or you could set another field on Lead with a hidden form field, and base your trigger logic on that.

  • 1
    great minds think alike (finally - hat tip to you for pointing out my epistemic arrogance) – cropredy Jul 9 '19 at 17:58
1

At beforeInsert time, the sobject's OwnerId field is always populated in Trigger.new. Thus, you need to change your code to test for OwnerID = The default lead owner (see Setup | Lead Settings and change the OwnerId accordingly. The default lead owner is used for W2L.

Unfortunately, LeadSettings is not available in the Metadata API (V46) as it is an unsupported type so you can't really robustify your code to be tolerant of any settings value.

The workaround hacks are discussed here in this SFSE Q&A. As such, for coding and testing, you may need to use custom settings, custom metadata, or custom labels to maintain an unsync'ed copy of the default lead owner

A better workaround is to use LeadSource='Web' as your clue that it is a W2L (or some other field you set ONLY on your W2L form.

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.