7

I have a class which contains only public static final strings how do i write a test class to cover this code?

public class SFA_MobileConstants {

 public static final string ERROR='ERROR';
 public static final string FAIL='FAIL';
 public static final string SUCCESS='SUCCESS';
 public static final string RECSAVEMSG='Record saved';

}


@istest
public class testconstants {

     public testMethod static void testSFA_MobileConstants(){

  System.assertEquals(SFA_MobileConstants.ERROR,SFA_MobileConstants.ERROR);     
  }

}

2 Answers 2

6

You should find that if you are testing the code that references these strings they should be covered. Otherwise add a test method to the class that references those strings.

public with sharing class TestStrings {

    public static final String TEST = 'MyString';

    @IsTest
    public static void testStrings()
    {
         System.assertEquals(TEST, TEST);
    }
}

If your variables and tests are in different classes, just be sure to qualify the class name.

public with sharing class TestStrings2 {

    @IsTest
    public static void testStrings()
    {
        System.assertEquals(TestString.TEST, TestString.TEST);
    }
}

In this case you really are just gaining coverage, as we expect the platform behaviour to work and of course provide consistently the strings we assign. So while you could do the same without the assert, it just feels wrong from a best practice point of view. And of course would raise the eye of the security scanner.

enter image description here

11
  • I tried but i cannot assign again values as its a final variable and simply assigning these into another variable not helping either Dec 17, 2012 at 9:16
  • Ok I assumed the strings are defined as in my answer, perhaps if you can publish a sample in your answer I can better understand what you mean. Dec 17, 2012 at 9:17
  • Mine is in separate class and the test code is in different class Dec 17, 2012 at 9:26
  • Andrew thanks for reply.I have given the code in my question Dec 17, 2012 at 9:28
  • No problem, I've updated my answer to show a test from another class referencing your static final variables from another. Dec 17, 2012 at 9:31
2

Please add a constructor like this:

public SFA_MobileConstants() {}

It will fix your issues.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .