Test Edge Cases and Exceptions
By the end of this lesson, you'll be able to:
- Test the exact validation boundaries (credit score 300 and 850)
- Test a batch containing both valid and invalid applications together
- Explain what happens to the whole batch when one record fails validation
Prerequisites: "Write Comprehensive Tests"
Testing the exact validation boundaries
@isTest
static void creditScoreOf300IsValid() {
LoanValidationService validator = new LoanValidationService();
validator.validate(10000, 50000, 300); // should not throw
System.assert(true);
}
@isTest
static void creditScoreOf299IsInvalid() {
LoanValidationService validator = new LoanValidationService();
try {
validator.validate(10000, 50000, 299);
System.assert(false, 'Expected a LoanValidationException');
} catch (LoanValidationException e) {
System.assert(e.getMessage().contains('Credit score'));
}
}
300 and 299 — the exact edge of the valid range — is precisely where a < vs <= mistake in LoanValidationService.validate() would hide, exactly like the 599/600 boundary from the previous lesson.
A batch with one invalid application
@isTest
static void oneInvalidApplicationInABatchBlocksTheWholeInsert() {
List<Loan_Application__c> applications = new List<Loan_Application__c>{
LoanTestDataFactory.createQualifyingApplication(),
LoanTestDataFactory.createApplication(-5000, 50000, 720) // invalid: negative amount
};
try {
insert applications;
System.assert(false, 'Expected a DmlException from the invalid second record');
} catch (DmlException e) {
System.assert(e.getMessage().contains('amount'));
}
System.assertEquals(0, [SELECT COUNT() FROM Loan_Application__c]);
}
Because beforeInsert throws an exception (via validate()) for the second application, the entire insert statement fails — not just the bad record. The final assertion confirms this explicitly: zero applications were saved, including the perfectly valid first one, exactly the all-or-nothing DML behavior from Module 19.
Exercise
Write a test confirming that inserting a batch of 3 valid applications and 1 with an out-of-range credit score (900) throws and saves nothing.
Show hint
Follow the try/System.assert(false)/catch pattern, then assert zero records were saved.
Test Edge Cases and Exceptions Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
This lesson tests the genuinely tricky edge cases: the exact validation boundaries, and — critically — what happens when a bulk insert mixes valid and invalid applications in the same batch.