Set CreatedById Field in Apex Test Class

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;


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.