Skip to content

Writing Tests

How to write tests

Test both positive and negative conditions.

Test all possible paths through code. If there seem to be a lot, it's probably time to refactor.

Use verbose names for your tests so it is clear what they are testing.

Keep tests small so different functionality is tested by different test methods.

If the tests require a lot of configuration or data records, create them in a @TestSetup method.

Name you test classes so they match the class being tested, with a _Test suffix. For example, tests for the HelloWorld class should be in a HelloWorld_Test class.

When fixing bugs, write a test first such that the test fails due to the bug. This helps you verify that you understand the bug.

Writing Assertions

  • When writing assertions, always use the optional msg parameter.

  • In general, use System.assertEquals (or System.assertNotEquals) rather than System.assert.

  • Remember that the expected value is the first parameter, and the actual value is the second parameter.

By following these guidelines, you make it clear to the reader what is being tested, and when a test fails, the error message makes sense, e.g.

System.assertEquals(5, 2*2, 'doubling two');

generates the error

Assertion Failed: doubling two: Expected: 5, Actual: 4

Example

Here is an example of a test class for Fizz Buzz.

@IsTest
private class FizzBuzz_Test {
    private static testMethod void convertNumber_should_return_fizz_if_divisible_by_3() {
        System.assertEquals('Fizz', FizzBuzz.convertNumber(3), 'converting 3');
        System.assertEquals('Fizz', FizzBuzz.convertNumber(6), 'converting 6');
        System.assertEquals('Fizz', FizzBuzz.convertNumber(300), 'converting 300');
    }

    private static testMethod void convertNumber_should_return_buzz_if_divisible_by_5() {
        System.assertEquals('Buzz', FizzBuzz.convertNumber(5), 'converting 5');
        System.assertEquals('Buzz', FizzBuzz.convertNumber(10), 'converting 10');
    }

    private static testMethod void convertNumber_should_return_fizzbuzz_if_divisible_by_3_and_5() {
        System.assertEquals('Fizz Buzz', FizzBuzz.convertNumber(15), 'converting 15');
        System.assertEquals('Fizz Buzz', FizzBuzz.convertNumber(30), 'converting 30');
    }

    private static testMethod void convertNumber_should_return_number_if_not_divisible_by_3_or_5() {
        System.assertEquals('1', FizzBuzz.convertNumber(1), 'converting 1');
        System.assertEquals('2', FizzBuzz.convertNumber(2), 'converting 2');
        System.assertEquals('22', FizzBuzz.convertNumber(22), 'converting 22');
    }

    private static testMethod void convertNumber_should_throw_an_exception_if_passed_an_unsupported_value() {
        Boolean failed = false;
        try {
            FizzBuzz.convertNumber(-1);
        } catch (FizzBuzz.UnsupportedNumberException e) {
            failed = true;
        }
        System.assertEquals(true, failed, 'exception thrown');
    }
}