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.00verifyTotal({ 10, 20 }, 10, 30.00)→ fails, because the total is wrongverifyRejected({ 10 }, 10)→ fails, because 10 is a valid price and nothing is thrown
Requirements:
verifyTotalasserts the result oftotalequalsexpected.verifyRejectedcallstotalinsidetryand callsAssert.failwhen nothing is thrown.- Its
catchhandlesIllegalArgumentExceptionand asserts the message equalsInvalid input. - Keep both methods public static, and keep the two
@IsTestmethods.
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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.