User Story
As a Salesforce administrator,
I want to mass update the UserRoleId
field to null for all users with existing roles,
so that I can reset user roles in bulk for further reassignment or role restructuring.
Apex Code
List<User> usersWithRoles = [SELECT Id, UserRoleId FROM User WHERE UserRoleId != null];
if (usersWithRoles != null && !usersWithRoles.isEmpty()) {
for (User u : usersWithRoles) {
u.UserRoleId = null;
}
update usersWithRoles;
}
Apex Class
public class UserRoleResetService {
public static void resetUserRoles() {
List<User> usersWithRoles = [SELECT Id, UserRoleId FROM User WHERE UserRoleId != null];
if (usersWithRoles != null && !usersWithRoles.isEmpty()) {
for (User u : usersWithRoles) {
u.UserRoleId = null;
}
update usersWithRoles;
}
}
}
Test Class
@IsTest
public class UserRoleResetServiceTest {
@TestSetup
static void setupTestData() {
List<User> testUsers = new List<User>();
for (Integer i = 0; i < 5; i++) {
User u = new User(
FirstName = 'Test',
LastName = 'User' + i,
Email = 'testuser' + i + '@example.com',
Username = 'testuser' + i + '@example.com',
Alias = 'tuser' + i,
TimeZoneSidKey = 'America/New_York',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
ProfileId = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1].Id,
LanguageLocaleKey = 'en_US',
UserRoleId = '00E000000000001'
);
testUsers.add(u);
}
insert testUsers;
}
@IsTest
static void testResetUserRoles() {
UserRoleResetService.resetUserRoles();
List<User> updatedUsers = [SELECT Id, UserRoleId FROM User WHERE UserRoleId != null];
System.assertEquals(0, updatedUsers.size(), 'UserRoleId should be null for all users');
}
}