Activity Forums Salesforce® Discussions How do you unit test a trigger when you don't know the required fields?

  • shradha jain

    Member
    August 17, 2018 at 5:44 am

    Hello Madhulika,

    Customers can have validation on custom fields via validation rules and triggers, so handling that in your unit tests without customer intervention is next to impossible. The first step to reducing issues is to have your test data populate all standard fields and ensure the data uses the most common formatting for your customer base (US style phone numbers and addresses for the US for example).

    Beyond that you can use the new Reflection features added to Salesforce in Summer '12 to allow customers to create unit test data classes that can be used by your managed package. Basically you define a test data generation interface and the customer creates an Apex class to generate data for you. Here's an example of using Reflection in a similar manner on the DeveloperForce blog: http://blogs.developerforce.com/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html.

    Using the method for unit tests run on install might be problematic as you'd have to have the customer create the class before they install your package and your package could only look for the class by name (or iterate through all default namespace classes and check for the correct interface). However, it's no longer necessary for unit tests to run during installation for managed packages and by default they do not.

    The Reflection method requires some coding knowledge on the customer side, but you could add a tool in your application to generate the custom unit test data class for the customer.

    FYI, it's no longer necessary for managed package unit tests to succeed in customer orgs. They're not required on install, they will no longer prevent deployment to production and they don't count as part of the customers unit test coverage percentage for purposes of deployment. The only exception to that is if the customer uses ANT and sets the runAllTests parameter to true.

    Thanks.

  • shariq

    Member
    September 17, 2018 at 11:08 pm

    Hi,

    You can take out the fields from schema class and fill those values respective to their display type but if there is a validation setup on some fields then you need to contact to your admin because without knowing the validation you can't unit test the code.

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos