3

I am facing a bizarre situation where test class coverage is 100% irrespective of how much logic is implemented in the test class. Below is the class

public with sharing class testconstants{
  public static string str1 ='firststring';
  public string str2='secondstring';
  public string str3='thirdstring';
}

The test class is

@isTest
public class testcontants_testclass{
  static testmethod void method1()
  {
    testconstants t = new testconstants();
    test.starttest();
    system.assertEquals(testconstants.str1,'firststring');
    test.stoptest();
  }
}

Now even if I am keeping two asserts (one for str1 and other for str2) or only one assert (as above) , the coverage is reaching 100%.

  • 3
    asserts are nothing to do with coverage. they are to verify if your code is behaving as expected. In your case your class doesn't hv any methods. so just creating an instance covers the variables and it will give you 100% coverage (irrespective of the asserts). – Vamsi Krishna May 2 '16 at 7:36
  • 2
    A class can be covered as a side effect of other tests running. Personally I wouldn't write a test for a class that only defines static constants as the test is then really only confirming that the compiler/runtime works and any change to the constants will require tedious change to the test. – Keith C May 2 '16 at 8:58
6

The coverage is not calculated based upon the Asserts. Asserts just used to check the functionality.

  • So the best practice in writing test classes for such classes that declare constants is to instantiate the class? adding assert statements for the strings are not necessary?- speaking from best practice point of view – starhunter May 2 '16 at 8:05
  • From salesforce security review perspective a test method should have an assert check. – Mr.Frodo May 2 '16 at 8:22
6

Coverage is calculated by the lines of code that your unit tests traverse (or "cover").

I think that, when your tests reference the testconstants, the class is loaded in memory and all the statics are initialized/brought into place (at least, that's how it would work in Java, and I assume Apex is similar). At that point, all your static members are covered.

If you added static and/or instance methods, you would need to call them to give them coverage.

I'm sure there are different opinions on what's best practice when testing a class that contains just constants. I prefer to test business behaviour rather than implementation details (see this excellent presentation by Ian Cooper). Unless those constants had some business value, I would simply not test that class.

5

Asserts are used to check whether you are getting the expected output at that point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.