Skip to main content

Code reviews rule: Untested Apex method

Written by David Martin
Updated this week

Untested Apex method

Why is this an issue?

Unit tests ensure that code meets quality standards before deployment. Untested methods pose several risks:

  • Bugs may go undetected by developers until end users start reporting issues

  • Refactoring becomes risky without tests to verify consistent behavior

  • Salesforce requires 75% code coverage for deployment, but 100% coverage of critical logic is recommended

Beyond meeting coverage requirements, meaningful tests validate that your code behaves correctly under various conditions.

Examples

Example method:

public class AccountService {
public static void deactivateAccount(Id accountId) {
Account acc = [SELECT Id, Status__c FROM Account WHERE Id = :accountId];
acc.Status__c = 'Inactive';
update acc;
}
}

Example of test coverage that would satisfy this rule:

@IsTest
private class AccountServiceTest {
@IsTest
static void testDeactivateAccount() {
Account acc = new Account(Name = 'Test', Status__c = 'Active');
insert acc;

Test.startTest();
AccountService.deactivateAccount(acc.Id);
Test.stopTest();

Account result = [SELECT Status__c FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Inactive', result.Status__c);
}
}

How can I fix violations?

Write test methods that exercise the untested code:

  1. Create a test class: If one doesn't exist, create a test class for the Apex class containing the untested method.

  2. Test positive scenarios: Verify the method works correctly with valid input.

  3. Test negative scenarios: Verify the method handles invalid input, null values, and edge cases appropriately.

  4. Use assertions: Include Assert.areEqual(), Assert.isTrue(), or similar assertions to verify expected outcomes.

@IsTest
private class AccountServiceTest {
@IsTest
static void testGetActiveAccounts() {
// Setup test data
Account testAccount = new Account(Name = 'Test', IsActive__c = true);
insert testAccount;

// Execute the method
Test.startTest();
List<Account> results = AccountService.getActiveAccounts();
Test.stopTest();

// Verify results
Assert.areEqual(1, results.size(), 'Should return one active account');
}
}

Resources

Did this answer your question?