Activity Forums Salesforce® Discussions Queries Related To Apex Test Class

  • Shubham

    Member
    June 14, 2016 at 7:38 am

    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 = '[email protected]';
    testUser.Alias = 'Tcode';
    testUser.Username = '[email protected]';
    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 8 years, 4 months ago by  Shubham.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos