Hi Ajit,
1) Yes you are correct, System method ‘runas’ enables you to write test methods that change the user context to the current user or a new user so that user record sharing is enforced. Here is a simple example in which a new user is created and the test class will run as that user.
`@isTest
private class TestClassName {
public static testMethod void testMethodName() {
// This code will runs as the system user
Profile p = [SELECT Id FROM Profile WHERE Name=’Standard User’];
User testUser = new user();
testUser.LastName = ‘Test Code’;
testUser.Email = ‘test@test.com’;
testUser.Alias = ‘Tcode’;
testUser.Username = ‘test1234444@test.com’;
testUser.CommunityNickname = ‘test12’;
testUser.LocaleSidKey = ‘en_US’;
testUser.TimeZoneSidKey = ‘GMT’;
testUser.ProfileID = p.Id;
testUser.LanguageLocaleKey = ‘en_US’;
testUser.EmailEncodingKey = ‘UTF-8’;
insert testUser;
System.runAs(testUser) {
// The following code runs as user ‘testUser’
System.debug(‘Current User: ‘ + UserInfo.getUserName());
System.debug(‘Current Profile: ‘ + UserInfo.getProfileId());
}
}
}
`
2. test.startTest() and test.stopTest() are used to mark the points from where your test actually begins & ends in your test class. So that before calling ‘test.startTest()’ you can set up data,initialize variables,everything you need to run your test. Any code executes after ‘test.startTest()’ will be assigned with new set of governor limits.
-
This reply was modified 9 years, 11 months ago by
Shubham.