I'm working on a feature contribution for an open source project that is distributed as a managed package (the Nonprofit Success Pack). The feature synchronizes custom fields across two related records of a custom object. The packaged fields on the object are all currently handled by the managed code - the new functionality is to enable end-users that add custom fields to the managed object to designate those fields to be synchronized in the same way that the packaged fields are.

The thing I'm struggling with is how to write test coverage for the code paths where an unmanaged custom field has been added and designated for synchronization. All the managed fields are involved in the existing automation. Essentially, I need to create test metadata in addition to then putting test data into those test fields.

Because it's an open source project and I want to keep my pull request as lean as possible, I'd prefer not to add the Apex MDAPI class. Any other options?


The Apex MDAPI won't help you with a unit test--you can't actually cause any real effect to the database in a unit test. Realistically, your best choice is to insert a custom setting that duplicates the effort of a field that's already synchronized by the package; if the code is written properly, it should not cause anything to crash.

While I'm not familiar with the package, I would say that if a set of standard synchronization fields and custom synchronization fields are using two separate pieces of code, that is not particularly DRY (Don't Repeat Yourself), and should be consolidated into a single unit of work (a common utility class). That way, you need only test a utility class to make sure it functions as it should, instead of maintaining two separate versions of essentially the same code.

| improve this answer | |
  • Using an existing packaged field had crossed my mind - it'll cover the lines, but the asserts will be pretty meaningless. Maybe that's the best I can do here. I am, btw, adding new logic and a couple methods to the existing class that handles the managed field behavior, so it's not duplicate code. – Thomas Taylor Jan 27 '17 at 4:30
  • 2
    @ThomasTaylor Unfortunately it's all you can do. Access to the MDAPI would require a callout, which means you'd be writing an HttpCalloutMock, which means... no actual new fields would be created anyways. This is one of those things we have to accept as "untestable" in the truest sense. The only other alternative I see would be to include a dummy field that's not automatically synchronized anywhere except in a unit test configured to do so, but I hate including fields or objects just for unit test purposes. It feels wrong somehow. – sfdcfox Jan 27 '17 at 4:35

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.