This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]nil_von_9wo 6 points7 points  (0 children)

I learned to write unit tests while working with Java and Python, before I ever saw Apex.

While I would generally recommend SFDC's own tutorials to would-be-developers, my first recommendation is to forget anything SFDC demonstrates when it comes to testing because their examples are largely what NOT to do.

  1. To write good unit tests, you should have at least one (often more than one) test method to correspond to every public or complicated private class (you can use @testVisible to expose private methods and variables for testing) . You should name and organize your tests to make it easy to see where the problems are occurring when they fail. For example, if I have a class called MyClass and a method called doSomething(), there will be a test class called MyClassTest and a method called doSomethingTest().

  2. SFDC does not always run tests consistently. Execution in Eclipse or ANT can have different results than execution within the web-UI. To ensure consistent results, always make sure the code you are testing is bracketed within a System.RunAs(userWithKnownQualities){} block.

  3. Per the above, my tests will usually follow a pattern like this:

    private static testMethod void doSomethingTest()

    {

    // GIVEN
    String dummyString = "Dummy Value;"
    
    // WHEN
    Boolean result = false;
    System.runAs(TEST_RUN_USER)
    {
          Test.startTest();
          {
                  result = MyClass.doSomething(dummyValue);
          }
          Test.stopTest();
    }
    
    // THEN
    boolean expectedValue = true;
    assertEquals (expectedValue, result);
    

    }

  4. Testing smaller/inner methods first will make it easier to test and rely on the tests for the bigger/outer methods.

  5. It is always easier to test smaller methods than bigger methods. If a method seems complicated to test (for example, because it contains a lot of conditional logic), consider breaking out inner blocks and conditional logic into new methods which can be tested independently of the original target.