2

Here is the scenario.

I have a custom field on Contact, which gets auto-populated in a trigger before-insert and before-update. All fine, but this is a field in an Managed Package. Where the package can be installed on an org which has Contacts already in the database. So I wrote a OnInstall batch job that just fetches contacts, where that field is blank, and updates them.

All works perfectly, but now it comes, how am i able to write a Unit Test for this? If I insert a contact in my test context, the field gets populated (because of the trigger), and will not be picked up by my script.

3

Accessing Existing Data

You can use the showAllData test annotation to allow you script access to the records already in the system; any changes of course will be rolled back at the end of your test. You'll probably want to limit the query to a single record (or a handful) as there could be tends of thousands!

The example given in the documentation:

@isTest(SeeAllData=true)
public class TestDataAccessClass {
    static testmethod void myTestMethod1() {
    // etc.

Alternative

I'm not a fan of having specific code present to try and increase test coverage, but if you need the coverage then you often have no choice.

I would add a public static boolean to my test class which is checked by the trigger on insert and update, if the boolean is true then it blanks the field in question, otherwise it behaves as normal.

In doing this you can now have it run either way inside your tests to maximise the coverage. If you just used Test.IsRunningTest() in the trigger thne it'd always behave the same way giving you less flexibility.

1
  • I went that road aswel, but unfortunately there aren't any contacts in my database without the field filled in, I could however disable the trigger, create a contact, and use it to test, but this all feels "unclean" :) – pjcarly Mar 7 '13 at 8:44

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.