.NET 7 added the UnreachableException class, which is meant to be thrown when executing a branch that isn't isn't expected to execute, due to the developer believing it to be unreachable. The Microsoft code coverage tools should analyze code that throws UnreachableException and reduce the number of coverable lines and branches accordingly.
Consider the following example:
using System.Diagnostics;
enum E
{
A,
B,
C,
}
static partial class C
{
public static void M()
{
E value = GetValue();
switch (value) // line 16
{
case E.A:
PerformActionA();
break;
case E.B:
PerformActionB();
break;
case E.C:
PerformActionC();
break;
default:
throw new UnreachableException(); // line 31
}
}
}
Currently, this will yield coverage data for M() like so:
We see that the condition on line 16 shows four branches (one of which is the default case and is uncovered) and that line 31 shows no hits. If the developer has otherwise guaranteed that GetValue() will return a valid value of E—one of the known enum cases—and they handle the remaining case in the above sample by throwing UnreachableException, the code coverage findings should reflect that. Given the above example, if the code coverage tools were aware of UnreachableException, I would instead expect to see the following coverage data:
Recognizing the developer's intent with regards to intentionally unreachable code will provide for more accurate code coverage results, and will make the tooling more usable for teams who want to enforce 100% code coverage in their test suites.
.NET 7 added the UnreachableException class, which is meant to be thrown when executing a branch that isn't isn't expected to execute, due to the developer believing it to be unreachable. The Microsoft code coverage tools should analyze code that throws UnreachableException and reduce the number of coverable lines and branches accordingly.
Consider the following example:
Currently, this will yield coverage data for
M()
like so:We see that the condition on line 16 shows four branches (one of which is the
default
case and is uncovered) and that line 31 shows no hits. If the developer has otherwise guaranteed thatGetValue()
will return a valid value ofE
—one of the known enum cases—and they handle the remaining case in the above sample by throwing UnreachableException, the code coverage findings should reflect that. Given the above example, if the code coverage tools were aware of UnreachableException, I would instead expect to see the following coverage data:Recognizing the developer's intent with regards to intentionally unreachable code will provide for more accurate code coverage results, and will make the tooling more usable for teams who want to enforce 100% code coverage in their test suites.
References: