Hi Salesforce Community,
I have created an Apex class named SingleEmailLimitController to check the daily single-email limit in my Salesforce organization. The class retrieves the email limit using System.OrgLimits.getMap() and returns the daily limit, emails used, emails remaining, and a status message.
I am trying to write an Apex test class to achieve 100% code coverage, but I am facing difficulties covering all the conditional branches and the exception-handling block.
My main challenges are:
- Testing the scenario where limits.get('SingleEmail') returns null.
- Covering the condition where the daily email limit has been reached or exceeded.
- Covering the condition where 10 or fewer emails remain.
- Covering the condition where sufficient email capacity remains.
- Covering the catch (Exception e) block.
- Testing these scenarios without depending on the actual email usage and limits of the Salesforce organization.
Since System.OrgLimits.getMap() returns system-provided limit information, I am unsure how to simulate these different scenarios in an Apex test.
My Apex controller:
public with sharing class SingleEmailLimitController {
public class EmailLimitResponse {
@InvocableVariable(label='Daily Single Email Limit')
public Integer dailyLimit;
@InvocableVariable(label='Emails Used')
public Integer emailsUsed;
@InvocableVariable(label='Emails Remaining')
public Integer emailsRemaining;
@InvocableVariable(label='Limit Status Message')
public String statusMessage;
}
@InvocableMethod(
label='Check Single Email Limit'
description='Checks daily email usage and returns a status message.'
)
public static List<EmailLimitResponse> checkSingleEmailLimit(
List<String> requests
) {
EmailLimitResponse result = new EmailLimitResponse();
List<EmailLimitResponse> results =
new List<EmailLimitResponse>();
try {
Map<String, System.OrgLimit> limits =
System.OrgLimits.getMap();
System.OrgLimit emailLimit = limits.get('SingleEmail');
if (emailLimit == null) {
result.statusMessage =
'Unable to retrieve the daily email limit.';
} else {
result.dailyLimit = emailLimit.getLimit();
result.emailsUsed = emailLimit.getValue();
result.emailsRemaining =
Math.max(
0,
result.dailyLimit - result.emailsUsed
);
if (result.emailsUsed >= result.dailyLimit) {
result.statusMessage =
'Daily email limit exceeded. No email capacity remains.';
} else if (result.emailsRemaining <= 10) {
result.statusMessage =
'Daily email limit almost reached. Only ' +
result.emailsRemaining + ' emails remaining.';
} else {
result.statusMessage =
'Email capacity available. ' +
result.emailsRemaining +
' emails remaining out of ' +
result.dailyLimit + '.';
}
}
} catch (Exception e) {
result.statusMessage =
'Unable to check email limit: ' + e.getMessage();
}
results.add(result);
return results;
}
}
My questions:
- Is it possible to achieve 100% code coverage for this controller without changing its implementation?
- If not, what is the recommended approach for making the limit values testable?
- How can I write a complete Apex test class that covers all the conditional branches and the exception-handling block?
- Would using a @TestVisible helper method or an injectable service be a suitable solution?
Please share a working example of the controller changes, if necessary, and the corresponding Apex test class.
Thank you for your help!
#Salesforce Developer #Salesforce Admin #Trailhead Challenges #Trailhead
Hi @HARIPRASAD Km Good question! Since System.OrgLimits.getMap() returns actual Salesforce org limits, you cannot directly mock its values in an Apex test class.
1. Recommended Approach
- Separate the Logic: Move the email limit calculations and status messages into a separate helper method.
- Use @TestVisible: Make the helper method accessible to test classes.
- Pass Test Values: Test the logic using different values instead of depending on actual org limits.
- Test All Conditions: Cover limit exceeded, 10 or fewer emails remaining, and sufficient capacity.
- Exception Handling: Use dependency injection with a test provider that throws an exception to cover the catch block.
- Null Scenario: Use an injectable provider to simulate missing limit information.
2. Simple Apex Example
@TestVisible
private static String getLimitStatus(
Integer dailyLimit,
Integer emailsUsed
) {
Integer remaining = Math.max(0, dailyLimit - emailsUsed);
if (emailsUsed >= dailyLimit) {
return 'Daily email limit exceeded.';
} else if (remaining <= 10) {
return 'Daily email limit almost reached.';
}
return 'Email capacity available.';
}
3. Test Different Scenarios
@IsTest
static void testEmailLimitStatus() {
System.assertEquals(
'Daily email limit exceeded.',
SingleEmailLimitController.getLimitStatus(100, 100)
);
System.assertEquals(
'Daily email limit almost reached.',
SingleEmailLimitController.getLimitStatus(100, 95)
);
System.assertEquals(
'Email capacity available.',
SingleEmailLimitController.getLimitStatus(100, 50)
);
}
4. Official Salesforce Documentation
My Suggestion: Use @TestVisible for simple logic testing and dependency injection when you need to simulate null values or exceptions.
Key Point:
Achieving 100% coverage reliably is difficult with the current implementation because it depends on live org limits. Refactoring makes your tests more predictable and independent.
Hope this helps! Venkat Yadav | SFDCINDIA