6

I have created a trigger on the Account object that is validated only if the records are being created by an non-admin account.

In order to test this functionality I would have to set the createdbyidfield in the test class, but when trying to do this I get the error:

Field is not writeable: Account.CreatedById

I know that for the CreatedDate field, even though normally is not writable it can be changed in a test environment.

Is the same functionality available for CreatedById field?

If not, are there any other workarounds that would allow me to test this scenario?

Any help would be much appreciated!

  • Couldn't you use the runAs method to make the code execute as a non Admin user? – Dave Humm May 13 '16 at 10:27
  • 1
    you can set created date using Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12)); in test class check sprint 16 release notes releasenotes.docs.salesforce.com/en-us/spring16/release-notes/… – Ratan Paul May 13 '16 at 10:32
  • @Ratan I know that about CreatedDate, but what about createdByid? – Marc Zaharescu May 13 '16 at 10:34
  • 1
    @MarcZaharescu you can use system.RunAs so you can insert your record in other user's context so salesforce will set the createdBYId for us. – Ratan Paul May 13 '16 at 10:35
9
User u = new User();
//put the user details you want for this user.
insert u;

System.runAs(u) {
 /* your record insert here */
 insert Account;
}

The account will have the createdById set as the User u;

2

There are several ways to accomplish this.

See this link: Setting system protected fields for test code coverage

It says:

There are 2 ways in which you can set system protected fields for test code coverage:

a) Using Test.loadData()

b) Using JSON.deserialize()

I would prefer the 2nd method.

Edit:

As already said in comments if you only want to execute the class under any given profile you can directly use System.runAs() method.

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.