Expected and actual arguments are transposed in an assertion
ID |
apex.maintainability.assert_arguments_order |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Test Quality |
Language |
Apex |
Description
Reports an assertEquals or assertNotEquals call whose literal sits in the second argument position, where the actual value belongs - the expected value is the first argument.
Rationale
The assertion decides the wording of its own failure message, and it trusts the order: System.assertEquals(actual, 'Acme') fails with "Expected: Acme-was-not-expected" reversed - it reports the value the code produced as the expectation and the constant as the result. Someone reading that failure in a pipeline log debugs the wrong side of the comparison, which is expensive precisely when the test was working.
The following code illustrates the pattern detected by this rule:
@IsTest
private class AssertOrderTest {
@IsTest
static void checksName() {
Account a = new Account(Name = 'Acme');
// FLAGGED: Expected and actual arguments are transposed in an assertion
System.assertEquals(a.Name, 'Acme');
// FLAGGED: Expected and actual arguments are transposed in an assertion
Assert.areEqual(a.Name, 'Acme', 'name is copied');
// FLAGGED: Expected and actual arguments are transposed in an assertion
System.assertEquals(a.Name.length(), 4);
System.assertEquals('Acme', a.Name);
Assert.areEqual('Acme', a.Name, 'name is copied');
System.assertEquals(1, a.Name.length());
System.assertEquals(4, a.Name.length(), 'four characters');
}
}