We are making heavy use of stub and mock objects in our Apex tests. Most of the time we are defining the mocks as inner classes of our test classes. We have noticed, that test classes, which do contain such mock classes do show up at the Overall Code Coverage in the developer console. Such a test class does always have a code coverage of 0% and 0/zz lines covered.
I give a short example. Consider the following class of the business logic:
public virtual class Foo {
public virtual String doSomething() {
return anotherFunction('foo');
}
public virtual String anotherFunction(String value) {
return value;
}
}
A typical unit test would look like the following:
@isTest
private class FooTest {
private class FooMock extends Foo {
private Boolean anotherFunctionCalled;
private String value;
public override String anotherFunction(String value) {
this.anotherFunctionCalled = true;
this.value = value;
return 'test';
}
}
@isTest
static void testDoSomething() {
FooMock f = new FooMock();
String result = f.doSomething();
System.assertEquals('test', result);
System.assertEquals(true, f.anotherFunctionCalled);
System.assertEquals('foo', f.value);
}
@isTest
static void testAnotherFunction() {
Foo f = new Foo();
String result = f.anotherFunction('blah');
System.assertEquals('blah', result);
}
}
The Overall Code Coverage shows the following:
Foo: 100% 4/4 Lines covered
FooTest: 0% 0/2 Lines covered
If you click on Apex Classes/Estimate your organization's code coverage you will get the surprising result of 66.67% (4/(2+4)) code coverage, which will not allow you to upload this code as a package.
How can we make sure, that the test classes will not be considered at the coverage estimation?
Error: Compile Error: FooTest.FooMock: Only top-level non-exception class types can be marked as tests at line 5 column 19