ApexSensei

Drills › Debug it

Fix a test that checks nothing

Debug it · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path

Scenario. The pricing tests have been green for a year. Last week a rounding bug reached production, and the tests never noticed.

A test class is green, yet a wrong total and a missing error both slip through. Add the asserts that make it fail when the code is wrong.

What you will learn

A test passes when nothing throws. So a test with no Assert passes whatever the code returns, and a try with an empty catch passes even when the error never happened.

Assert.areEqual(expected, actual, 'Wrong total');
try {
    service.run(badInput);
    Assert.fail('Expected an error');
} catch (IllegalArgumentException error) {
    Assert.areEqual('Invalid input', error.getMessage());
}

Gotcha. Assert.fail throws an assert exception. That catch does not catch it.

The task

Fix both verifiers so a wrong total, a missing error and a wrong error message each make the test fail.

Examples:

  • verifyTotal({ 10, 20 }, 10, 33.00) → passes, because 30 plus 10% tax is 33.00
  • verifyTotal({ 10, 20 }, 10, 30.00) → fails, because the total is wrong
  • verifyRejected({ 10 }, 10) → fails, because 10 is a valid price and nothing is thrown

Requirements:

  1. verifyTotal asserts the result of total equals expected.
  2. verifyRejected calls total inside try and calls Assert.fail when nothing is thrown.
  3. Its catch handles IllegalArgumentException and asserts the message equals Invalid input.
  4. Keep both methods public static, and keep the two @IsTest methods.

Starter code

@IsTest
public class AS_98EF88F18834_PricingTests {
    public static void verifyTotal(List<Decimal> prices, Decimal taxRate, Decimal expected) {
        Decimal result = AS_98EF88F18834_Pricing.total(prices, taxRate);
        System.debug('Total: ' + result);
    }

    public static void verifyRejected(List<Decimal> prices, Decimal taxRate) {
        try {
            AS_98EF88F18834_Pricing.total(prices, taxRate);
        } catch (IllegalArgumentException error) {
            System.debug('Rejected: ' + error.getMessage());
        }
    }

    @IsTest
    static void totalsTwoPrices() {
        verifyTotal(new List<Decimal>{ 10, 20 }, 10, 33.00);
    }

    @IsTest
    static void rejectsANegativePrice() {
        verifyRejected(new List<Decimal>{ -5 }, 10);
    }
}

When it passes

With the right expectations the verifiers pass. With a wrong total, a missing error or a wrong message, they fail with an assert.

Try this drill free

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

‹ Fix DML inside a loop · Stop a trigger calling itself ›