ApexSensei

Drills › Prove it with tests

Test success and exceptions

Prove it with tests · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A pricing service must work out valid discounts and reject bad input the same way every time.

Write verifiers that fail on a wrong amount, a wrong error message or a missing error.

What you will learn

Test the happy path and the error path. Call the method inside try. If nothing is thrown, Assert.fail(message) stops the test. It works inside try, because an assert failure can't be caught.

try {
    Discount.apply(100, 101);
    Assert.fail('Expected an error.');
} catch (IllegalArgumentException error) {
    Assert.areEqual('Invalid discount', error.getMessage());
}

Gotcha. catch (Exception error) also catches the wrong error, like a null pointer.

The task

Finish both verifiers so a wrong amount, a wrong message or a missing error all fail the test.

Examples:

  • amount 100, discount 15, expected 85.00 → passes and returns 85.00
  • amount -1, discount 10 → the service throws Invalid discount
  • verifyRejected(100, 15, 'Invalid discount') → the test fails, because 15% is valid and nothing is thrown

Requirements:

  1. verifySuccess asserts that the service result equals expected, then returns it.
  2. verifyRejected calls the service inside try and calls Assert.fail when nothing is thrown.
  3. It catches IllegalArgumentException, asserts the message equals expectedMessage, and returns the message.
  4. Keep both methods public static. The checks call them with right and wrong expectations.

Starter code

@IsTest
public class AS_ECE22D24B8C0_DiscountTests {
    public static Decimal verifySuccess(Decimal amount, Decimal percent, Decimal expected) {
        Decimal actual = AS_ECE22D24B8C0_Discount.apply(amount, percent);
        return null;
    }

    public static String verifyRejected(Decimal amount, Decimal percent, String expectedMessage) {
        return null;
    }

    @IsTest
    static void validDiscount() {
        verifySuccess(100, 15, 85.00);
    }
}

When it passes

verifySuccess fails on a wrong amount. verifyRejected fails when nothing is thrown or the message is wrong, and returns the message when it matches.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Build a test data factory · Check partial DML results ›