I have a custom setting which holds all the fields of an object. If i created a new custom field on the object it is need to get inserted into custom setting and for this i have written code which is working fine, now issue is to get the code coverage for this piece of code i need to create a custom field.

How to create a custom field in a object from test class?


If its only for code coverage

you can use System.Test.isRunningTest() to get the coverage

if(!sr.IsSuccess() || System.Test.isRunningTest()) 
// your code to be covered

You can't. The metadata API is, sadly, still unavailable via Apex.

I've heard of some hacks involving web service callouts to the Metadata API via Apex, but can't vouch for them, and this doesn't sound like a case that warrants that. (EDIT: plus you can't do callouts in test methods, of course, so that is not an option.)

  • You cannot make Web Service calls in test full stop, so even the hacks won't work in this case. ;-) – Andrew Fawcett Apr 25 '13 at 12:50

In this situation, it will likely not make much difference to your code if you give it an existing field say on Opportunity or Account. If you need a custom object and field that matches a more specific configuration you can create an object in your package just for this purpose. Make sure you don't reference it explicitly, only via Dynamic Apex. Then when you come to package it will not be included. For added safety incase your test gets run in the subscriber org, have it test for existence of the test object and fail gracefully.

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.