How can I fake setting some read-only fields in a unit test? I would like to avoid saving data...

Account testAccount = new Account(name = "Foobar", id = generateId(Account.sobjectType));
Lead testLead = new Lead(
  name = "Buzbar", 
  id = generateId(Lead.sobjectType),
  isConverted = true,
  convertedAccount = testAccount  // Field is not writeable: ConvertedAccount

I get this error:

Field is not writeable: ConvertedAccount.

Also, I tried using testLead.putSObject('ConvertedAccount', testAccount); but that fails at runtime.

How can I mock this?

3 Answers 3


You can use JSON and deserialization:

String payload = '{"ConvertedAccountId": "001000000000000"}';
Lead record = (Lead)JSON.deserialize(payload, Lead.class);
system.assertNotEquals(null, record.ConvertedAccountId);

If you wanted to instead set the name pointing reference, you would need to specify an object payload instead:

String payload = '{"ConvertedAccount": {"Id": "001000000000000"}}';
Lead record = (Lead)JSON.deserialize(payload, Lead.class);
system.assertNotEquals(null, record.ConvertedAccount);

All of this payload building might be easier (and certainly cleaner) if you serialize a Map<String, Object>:

String payload = JSON.serialize(new Map<String, Object>{
    'ConvertedAccount' => new Account(Id='001'.rightPad(15, '0'))
  • the isConverted works fine. i just need the sobjects for account, contact, and opportunity set. Commented Apr 4, 2017 at 15:24
  • @DanielA.White Same concept still applies.
    – Adrian Larson
    Commented Apr 4, 2017 at 15:26
  • how can i get the account details into the lead object - like name for instance? Commented Apr 4, 2017 at 15:27
  • You could set fields on record just like if you constructed it (record.Name = 'abc';). Or you could add it to the payload.
    – Adrian Larson
    Commented Apr 4, 2017 at 15:28
  • hm k. thx i'll give this a test... Commented Apr 4, 2017 at 15:28

I found it much easier if I created my own proxy/wrapper Apex class than using the built in Lead class. That way I could manipulate the instance as I saw fit instead of creating many objects to test with.


You could use an interface and dependency injection to create a FieldReader class that accepts mock values in these fields:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .