What the tests have to prove
Coverage percentage is not the goal; the acceptance criteria are. Each test here maps to one: routing spreads work, access follows the region, a bulk of 200 stays inside the limits, and the LWC’s controller fails politely.
A data factory
Every test builds its data the same way, through one class. If a required field is added to Referral__c, one file changes and the suite keeps passing.
@IsTest
public with sharing class TestDataFactory {
/** Coordinators for a region: users in its public group, with the coordinator permission set. */
public static void createCoordinators(String region, Integer count) {
Profile standard = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
PermissionSet coordinatorSet = [SELECT Id FROM PermissionSet WHERE Name = 'Referral_Coordinator' LIMIT 1];
String groupName = Referral_Routing__mdt.getInstance(region).Coordinator_Group__c;
Group regionGroup = [SELECT Id FROM Group WHERE DeveloperName = :groupName AND Type = 'Regular' LIMIT 1];
List<User> users = new List<User>();
for (Integer i = 0; i < count; i++) {
String stamp = region.toLowerCase() + i + '.' + Crypto.getRandomInteger();
users.add(new User(
FirstName = 'Sample', LastName = 'Coordinator ' + region, Alias = 'c' + i + region.left(3),
Username = stamp + '@referrals.example.com', Email = stamp + '@referrals.example.com',
ProfileId = standard.Id, EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US', TimeZoneSidKey = 'Europe/London'
));
}
insert users;
List<GroupMember> members = new List<GroupMember>();
List<PermissionSetAssignment> assignments = new List<PermissionSetAssignment>();
for (User u : users) {
members.add(new GroupMember(GroupId = regionGroup.Id, UserOrGroupId = u.Id));
assignments.add(new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = coordinatorSet.Id));
}
insert members;
insert assignments;
}
public static List<User> coordinators(String region) {
String lastName = 'Coordinator ' + region;
return [SELECT Id FROM User WHERE LastName = :lastName AND IsActive = true ORDER BY Id];
}
public static List<Referral__c> referrals(Integer count, String region, Boolean doInsert) {
List<Referral__c> records = new List<Referral__c>();
for (Integer i = 0; i < count; i++) {
records.add(new Referral__c(Region__c = region, Status__c = 'New', Priority__c = 'Routine'));
}
if (doInsert) insert records;
return records;
}
}Users, groups, group members and permission set assignments are setup objects. Creating them in @TestSetup, apart from the test method’s own Referral__c inserts, avoids the MIXED_DML_OPERATION error that appears when both kinds are saved in one transaction.
Two hundred records, in one transaction
The test that matters most for a trigger. It moves 200 referrals to another region in a single update, then asserts four things: every referral got a South coordinator, the work is spread between them, the North group lost every row and the South group gained them, and the whole thing used a small, fixed number of queries.
@IsTest
private class ReferralBulkTest {
@TestSetup
static void setup() {
TestDataFactory.createCoordinators('North', 2);
TestDataFactory.createCoordinators('South', 2);
}
@IsTest
static void movingTwoHundredReferrals_routesSharesAndStaysInLimits() {
List<Referral__c> referrals = TestDataFactory.referrals(200, 'North', true);
for (Referral__c r : referrals) r.Region__c = 'South';
Test.startTest();
update referrals;
Integer queries = Limits.getQueries();
Test.stopTest();
Assert.isTrue(queries <= 12, 'Routing and sharing must not query per record. Used ' + queries);
Set<Id> south = new Map<Id, User>(TestDataFactory.coordinators('South')).keySet();
Map<Id, Integer> perCoordinator = new Map<Id, Integer>();
for (Referral__c r : [SELECT Assigned_Coordinator__c FROM Referral__c]) {
Assert.isTrue(south.contains(r.Assigned_Coordinator__c), 'Every referral goes to a South coordinator.');
perCoordinator.put(r.Assigned_Coordinator__c, (perCoordinator.get(r.Assigned_Coordinator__c) ?? 0) + 1);
}
for (Integer n : perCoordinator.values()) {
Assert.areEqual(100, n, 'Two coordinators share 200 referrals evenly.');
}
Map<String, Id> groups = CoordinatorSelector.groupIdsByRegion(new Set<String>{ 'North', 'South' });
Assert.areEqual(200, shareCount(groups.get('South')));
Assert.areEqual(0, shareCount(groups.get('North')), 'Stale North access is revoked.');
}
private static Integer shareCount(Id groupId) {
return [SELECT COUNT() FROM Referral__Share
WHERE UserOrGroupId = :groupId
AND RowCause = :Schema.Referral__Share.RowCause.Regional_Coordination__c];
}
}Notes on the assertions:
Test.startTest()resets the governor counters, soLimits.getQueries()right after theupdateis the cost of that statement alone. The number is generous on purpose (the code uses about six); the point is that it does not depend on 200.- The least-loaded rule is tested through its effect (an even split), not by peeking at private state. If someone changes the counting inside the batch, 200 referrals piling onto one coordinator fails the test.
- Running the 200 inserts through the real trigger also exercises the before and after paths, the selectors and the sharing writes together.
The board controller fails politely
The wrapper controller is tested for its success shape and for its error path, including the setMessage detail from the wrappers page.
@IsTest
private class ReferralBoardControllerTest {
@TestSetup
static void setup() {
TestDataFactory.createCoordinators('North', 1);
}
@IsTest
static void getBoard_returnsTheCoordinatorsOwnReferrals() {
User coordinator = TestDataFactory.coordinators('North')[0];
TestDataFactory.referrals(3, 'North', true); // routing assigns them to the only North coordinator
ReferralBoardDto board;
System.runAs(coordinator) {
board = ReferralBoardController.getBoard(25);
}
Assert.areEqual(3, board.cards.size());
Assert.isTrue(board.cards[0].canEdit, 'Access granted by Apex sharing shows up as canEdit.');
}
@IsTest
static void getBoard_withoutObjectAccess_throwsAFriendlyMessage() {
User coordinator = TestDataFactory.coordinators('North')[0];
delete [SELECT Id FROM PermissionSetAssignment
WHERE AssigneeId = :coordinator.Id AND PermissionSet.Name = 'Referral_Coordinator'];
try {
System.runAs(coordinator) {
ReferralBoardController.getBoard(25);
}
Assert.fail('USER_MODE must refuse a user without access to Referral__c.');
} catch (AuraHandledException e) {
Assert.areEqual('You do not have access to some of the data this board needs.', e.getMessage());
}
}
}The second test removes the permission set from the coordinator and expects the safe sentence, not a raw QueryException. It also proves the setMessage call: without it, getMessage() would return a generic string and this assertion would fail. Both tests assume the regional groups contain only test users, which is true in a scratch org or a sandbox that has not been populated.