1

I have a class with the code below that I am trying to test. I am still very new to Apex and not sure I understand what I am supposed to do with the "(Object data)" part. I tried testing by inserting a new user as "usr" and then calling

String res = UserSearch.updateUser(usr);

But then I got a malformed JSON error message - "System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set".

How do I test this?

public inherited sharing class UserSearch {
@AuraEnabled
public static string updateUser(Object data){
    system.debug(data);
    List<User> v1 = (List<User>) JSON.deserialize(
        JSON.serialize(data),
        List<User>.class
    );
    List<User> userForUpdate = v1;
    try{
        update userForUpdate;
        return 'Success: Users Updated Successfully';
    }
    catch(Exception e){
        //return 'The Following exceptions have occured:' +e.getMessage();
        throw new AuraHandledException(e.getMessage());
    }
}

}

1 Answer 1

1

That's a horribly inefficient way to use Apex. You can pass in a list of user records directly:

@AuraEnabled public static String updateUser(User[] users) {
  try {
    update users;
  } catch(Exception e) {
    throw new AuraHanledException(e.getMessage());
  }
}

The only extra step is that your LWC/Aura must include the sobjectType property:

updateUser({ users: [ { sobjectType: 'User', id: '005...userid', isActive: true } ] });

This trivializes your unit test to something like:

@isTest static void testSuccess() {
  User testUser = new User( /* Include necessary fields here */ );
  String result = UserSearch.updateUser(new User[] { testUser } );
  // Don't forget to check the results
  Assert.areEqual('Success: Users Updated Successfully', result, 'Expected successful status');
}

As for the actual error you were getting, I presume you passed in bad data; if you wanted to start from your existing code, you'd write something like:

Object data = new List<Object> {
  new Map<String, Object> {
    'Id' => someUser.Id,
    'IsActive' => true /* ... etc */
  }
};

And to test that:

String result = UserSearch.updateUser(data);

In general, though, I'd recommend avoiding the serialize/deserialize round-trip unless you need to, it's simply inefficient and bloats the code unnecessarily.

The error message you received is because you passed in an object that wasn't a List/Set, so when it tried to deserialize, you got the error. An example that would cause the exception you received:

Object data = new Map<String, Object> {
  'Id' => someUser.Id,
  'IsActive' => true /* ... etc */
};
String result = UserSearch.updateUser(data);

Here, because data is a Map, JSON.serialize will start off with a {}, but JSON.deserialize will expect [], because your code is trying to deserialize to a List<User>.

1
  • Thanks! Worked perfectly. Commented Jan 18, 2023 at 5:57

You must log in to answer this question.

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