0

how may I update own user profile? I have below code I need update user field of runAs user

   @isTest
static void xyzMethod() {
    Boolean errofFlag= true;
    User userXYZ= createUserWithProfile('XYZ');
    Test.startTest();
    System.runAs(userXYZ) {
        userXYZ.Phone = '000222333';

        try {
            update userXYZ;
        } catch (Exception e){
            errorFlag= false;
        }
    }
    Test.stopTest();
    System.assertEquals(false, errorFlag);
}
4
  • 1
    We will need to know what you are trying to accomplish, possibly a little bit about why, and what you've tried that is not working in your test. As this question is written, it will be difficult to assist you.
    – Mark Pond
    Jul 23 '20 at 19:59
  • I only need to update a some field of running user (update own profile details) Jul 23 '20 at 20:03
  • For Example we have a userXYZ and I would like to update a phone field of this user but running as this user (update own details in test) Jul 23 '20 at 20:04
  • 1
    You seem to have done that. What is the specific problem with this code? Please edit to clarify rather than commenting.
    – David Reed
    Jul 23 '20 at 20:24
3

Your code looks fine, aside from the flawed logic in the catch block and the assertion that isn't doing anything truly useful.

You might consider writing your test in this pattern instead.

@isTest
private class yourTests {
  @isTest
  static void userCanUpdateTheirPhoneNumber() {
    // create user
    User userXYZ = createUserWithProfile('XYZ');

    Test.startTest();
    System.runAs(userXYZ) {
      // set the user's phone number
      userXYZ.Phone = '000222333';

      try {
        // try the update operation as this running user
        update userXYZ;
      } catch (Exception e) {
        system.assert(
          false,
          'The user was not able to update their own phone number. ' +
          e.getMessage()
        );
      }
    }
    Test.stopTest();
  }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.