Wherever possible I use TDD:
- I mock out my interfaces
- I use IOC so my mocked ojbects can be injected
- I ensure my tests run and that the coverage increases and I am happy.
then...
- I create derived classes that actually do stuff, like going to a database, or writing to a message queue etc.
This is where code coverage decreases - and I feel sad.
But then, I liberally spread [CoverageExclude]
over these concrete classes and coverage goes up again.
But then instead of feeling sad, I feel dirty. I somehow feel like I'm cheating even though it's not possible to unit-test the concrete classes.
I'm interested in hearing how your projects are organised, i.e. how do you physically arrange code that can be tested against code that can't be tested.
I'm thinking that perhaps a nice solution would be to separate out untestable concrete types into their own assembly and then ban the use of [CoverageExclude]
in the assemblies that do contain testable code. This'd also make it easier to create an NDepend rule to fail the build when this attribute is incorrectly found in the testable assemblies.
Edit: the essense of this question touches on the fact that you can test the things that USE your mocked interfaces but you can't (or shouldn't!) UNIT-test the objects that ARE the real implementations of those interfaces. Here's an example:
public void ApplyPatchAndReboot( )
{
_patcher.ApplyPatch( ) ;
_rebooter.Reboot( ) ;
}
patcher and rebooter are injected in the constructor:
public SystemUpdater(IApplyPatches patcher, IRebootTheSystem rebooter)...
The unit test looks like:
public void should_reboot_the_system( )
{
... new SystemUpdater(mockedPatcher, mockedRebooter);
update.ApplyPatchAndReboot( );
}
This works fine - my UNIT-TEST coverage is 100%. I now write:
public class ReallyRebootTheSystemForReal : IRebootTheSystem
{
... call some API to really (REALLY!) reboot
}
My UNIT-TEST coverage goes down and there's no way to UNIT-TEST the new class. Sure, I'll add a functional test and run it when I've got 20 minutes to spare(!).
So, I suppose my question boils down to the fact that it's nice to have near 100% UNIT-TEST coverage. Said another way, it's nice to be able to unit-test near 100% of the behaviour of the system. In the above example, the BEHAVIOUR of the patcher should reboot the machine. This we can verify
for sure. The ReallyRebootTheSytemForReal
type isn't strictly just behaviour - it has side effects which means it can't be unit-tested. Since it can't be unit-test it affects the test-coverage percentage. So,
- Does it matter that these things reduce unit-test coverage percantage?
- Should they be segregated into their own assemblies where people expect 0% UNIT-TEST coverage?
- Should concrete types like this be so small (in Cyclomatic Complexity) that a unit-test (or otherwise) is superfluous