Is there a way to exclude private methods from the tests, such that the black bar is not generated for private methods, and their code coverage doesn't affect the code coverage of the class under test?
1 Answers
To exclude any method from the code coverage you can use the [ExcludeFromCodeCoverageAttribute]
. I believe that NCrunch will honor this attribute.
You can also use comments to exclude code from code coverage. Details are explained in the documentation. How it works:
NCrunch recognises 3 different types of coverage suppression comments:
- //ncrunch: no coverage start - Marks the beginning of a block of code with code coverage suppression.
- //ncrunch: no coverage end - Marks the end of a block of code with code coverage suppression.
- //ncrunch: no coverage - Marks an individual line of code for code coverage suppression (place at the end of the line).
When working with a language other than C#, simply replace the '//' comment syntax with a syntax that is specific to your language.
I would question why you want to exclude private methods from the code coverage calculation though? surely they are methods in your class that need testing?
EDIT
Just because your methods are private it doesn't mean that they should not be covered by your tests. Your tests should be testing either the external behaviour of your class (when I give these inputs I get these outputs) or the internal interactions of you class with its dependencies (when I call this method with these values my class calls this method of its dependent object). The fact that some methods on your class are private is an irrelevant implementation detail. If your tests call your class but cannot exercise your private methods then this is likely an indicator of some other issue with your class, like it is doing too much.
Do you have a real example of the private methods that you want to exclude from code coverage, maybe we can help see if there is some other issue at play here.

- 32,535
- 13
- 101
- 181
-
Well, because the private methods are not accessible in my test project. – kasperhj Aug 03 '14 at 19:08
-
@lejon I have edited my answer to add more detail based on your comment. Seeing the actual code that is not covered by your tests might be useful. – Sam Holder Aug 04 '14 at 09:38
-
Maybe private methods have db dependencies etc.. In this case even if you make your method public virtual and override it, nCrunch still complains about code is not covered. – Teoman shipahi Jan 14 '15 at 00:48
-
"The fact that some methods on your class are private is an irrelevant implementation detail." - very well put. – glosrob Nov 02 '15 at 18:48
-
its best practice to "test the interface, not the implementation", the private methods will be covered by calling the public methods, or not called at all – Ewan Apr 30 '21 at 09:35