Test method contains no assertion
ID |
apex.correctness.unit_test_asserts |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Test Quality |
Language |
Apex |
Description
Reports an @IsTest method whose body contains no System.assert*, no Assert.* and no call to a helper whose name starts with assert.
Rationale
A test method with no assertion passes as long as the code under test does not throw. It runs the lines, it raises the coverage number Salesforce requires to deploy, and it reports success whatever the code produced - so a wrong total, a missing field or an inverted condition ships with a green test behind it. Coverage without assertions is the worst kind of test: it costs deployment time and buys no protection, and it hides the absence of a real check from anyone reading the run summary.
The following code illustrates the pattern detected by this rule:
@IsTest
private class OrderServiceTest {
@TestSetup
static void setup() {
insert new Account(Name = 'Acme');
}
// FLAGGED: Test method contains no assertion
@IsTest
static void discountIsApplied() {
Order o = new Order(TotalAmount = 100);
OrderService.applyDiscount(o);
System.debug(o.TotalAmount);
}
// FLAGGED: Test method contains no assertion
@isTest
static void orderIsPersisted() {
insert new Order(TotalAmount = 10);
}
@IsTest
static void discountIsApplied2() {
Order o = new Order(TotalAmount = 100);
OrderService.applyDiscount(o);
System.assertEquals(90, o.TotalAmount, 'a 10% discount was expected');
}
@IsTest
static void usesNewAssertClass() {
Assert.areEqual(1, 1, 'the new Assert class counts too');
}
@IsTest
static void delegatesToHelper() {
assertOrderTotal(new Order(TotalAmount = 10), 10);
}
static void assertOrderTotal(Order o, Decimal expected) {
System.assertEquals(expected, o.TotalAmount, 'total');
}
}
Remediation
Assert the behaviour the method is named after: compare the value the code produced against the value it should produce, with a message saying what was expected. Where the test exists to prove that an operation is rejected, assert on the caught exception’s message rather than on the absence of a failure.