7

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!

4
  • Couldn't you use the runAs method to make the code execute as a non Admin user?
    – Dave Humm
    Commented May 13, 2016 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
    Commented May 13, 2016 at 10:32
  • @Ratan I know that about CreatedDate, but what about createdByid? Commented May 13, 2016 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
    Commented May 13, 2016 at 10:35

2 Answers 2

10
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;

3

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.

You must log in to answer this question.

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