[SalesForce] create/update/delete metadata using APEX

In particular, I want to create a custom field for Task for a specific unit test, then delete that field when the test is finished.

I know Salesforce uses the Metadata API, but this seems designed to be used externally (via REST or SOAP web services).

I am also aware that there is a separate development, APEX Metadata API, that allows us to access said API via Apex (by making Web service calls!): https://github.com/financialforcedev/apex-mdapi

Is there a way of calling into the Metadata API natively? Or, to make the problem scope smaller, can I create/delete custom Task fields via APEX?

Thanks

Edit: there seems to be some confusion as to why I want to do this. Basically, I'm creating a managed package, which can be installed by different customers in their respective orgs. Each and every org will be customised in a different way, so I cannot make any assumption as to what these customisations will be.

What I want to test is how a certain part of my code that deals with tasks will behave in the presence of some custom fields. That is why I wanted to create a field, run my code, then delete the field, in the context of a unit test.

I considered the question answered, as 2 people have come back to me telling me that I cannot modify metadata from APEX.

Best Answer

The Apex testing framework is built to test functionality implemented in Apex.

But there is a lot more functionality in an org than just Apex, so a natural extension of this test functionality is to want to begin to test other functionality. In some cases, the natural features of the Apex test framework align quite closely.

Take for example workflow actions like field updates and assigning tasks. Because these are both data-oriented features, you could easily test the functionality of those features.

But many features do not align with Apex test functionality, most especially configuration/metadata changes.

Furthermore, the testing framework works primarily in the context of the runtime transaction model and is designed to leave no footprint either inside of the org (ringfencing of real data, no commits to data changes, and automatic rollback of DML) and in systems that are integrated with the org (no callouts allowed).

I think the tests you propose are a very good idea. I just think you will need to use an external testing framework to do so. With greater and greater support of config changes in the metadata and tooling API, these kinds of processes are becoming easier to automate.

Perhaps you could adapt your existing build process to perform this test. In other words after you deploy to your sandbox/trialforce org, automate a follow on process to deploy some metadata changes and then rerun all tests.

Related Topic