0

Should mock classes always be annotated with @IsTest? Are the reasons not to annotate them?

The reason that I'm asking is that I stumbled upon a mock class with a custom constructor for testing that used @IsTest and was missing two lines of coverage in that particular constructor. Missing coverage doesn't make sense with @IsTest as it should be exempt - so I suspect some kind of tooling issue somewhere. Interestingly the Salesforce UI itself correctly reports it as either exempt with @IsTest or fully covered without the annotation. I just wanted to make sure that mock classes belong in the test context and should be annotated as such.

1 Answer 1

3

Top-level classes marked @isTest do not require code coverage, and will not appear in code coverage reports. In addition, inner classes inside unit test classes do not require coverage. If you're going to use top-level classes for test mocks, you should mark them as @isTest so they are exempt from code coverage. Alternatively, you can also write inner classes that are mocks that won't require coverage.

5
  • The test classes are, of course, annotated. Since I'm using a top-level mock class, it felt correct to annotate the mock class as well. But why does it seem that I need to remove the annotation from a mock class if it is only used for testing?
    – Semmel
    Commented Feb 12 at 20:28
  • 2
    @Semmel What problem are you having? You may have asked an X-Y Problem. You shouldn't need to remove the annotation, and code coverage should not be required.
    – sfdcfox
    Commented Feb 12 at 20:33
  • Thanks for the clarification. My main question is if a mock class should be annotated with @IsTest (as it is only used for testing). I'll update the question accordingly.
    – Semmel
    Commented Feb 12 at 21:15
  • 1
    @Semmel All classes that are used only for test purposes should be marked as @isTest. This includes mocks, stubs, test data utilities, and so on.
    – sfdcfox
    Commented Feb 12 at 21:24
  • That's what I thought. So I guess it was just that weird behavior that was confusing me briefly. Sometimes the UI and tooling don't quite work well in tandem. Hopefully, I made the question clear enough now - I appreciate the feedback.
    – Semmel
    Commented Feb 12 at 21:29

You must log in to answer this question.

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