C# Exception Code Coverage in Azure DevOps

Hi,

We are using SonarCloud for code analysis in Azure DevOps on a C# .NET Core application.

There is a recurring issue with lines throwing exceptions showing as uncovered, as shown below

The total code coverage for this file is shown as 36.8%, with all of the thrown exceptions being highlighted as uncovered.

However, these exceptions are being explicitly tested in a test file using xUnit:

    [Fact]
    public void It_should_not_allow_empty_importance_value()
    {
        try
        {
            _validator.ValidateImportance("", 0);
        }
        catch (FileFormatException ex)
        {
            Assert.Equal("Missing importance value in row 1", ex.Message);
        }            
    }

the ‘Assert.Throws’ assertion was also used:

    [Fact]
    public void It_should_not_allow_empty_importance_value()
    {
        Assert.Throws<FileFormatException>(() => _validator.ValidateImportance("", 0));           
    }

Inspecting the .coverage file generated by the build pipeline showed this file as 100% covered:
sonar2

The Prepare Analysis Configuration task is configured as follows, excluding certain files from analysis:

# Additional properties that will be passed to the scanner, 
# Put one key=value per line, example:
sonar.exclusions=**/*.bin,**/WebApi/Migrations/*,**Tests.Unit/*,**Tests.Integration/*,**/WebApi/Extensions/EfCoreExtensions.cs
sonar.cs.vstest.reportsPaths=$(Agent.TempDirectory)/TestResults/*.trx

Running the tests locally returns 100% coverage for the given file.

Is there an issue with C# code coverage of exceptions? This has been an issue throughout the project where thrown exceptions are shown as not being covered.

Please let me know if any additional information is needed. Any suggestions are appreciated. Thanks!

hi @alext and welcome to this community!

would it be possible to come up with a minimal reproducible project and send it, together with the code coverage file for it, so we can reproduce it locally and investigate the problem?

Also, please let us know more details about the environment:

  • What visual studio coverage tool version are you using?
  • what is the version of Scanner for MSBuild you are using?
  • what is the version of MSBuild you are using?

I imagine you also pass the sonar.cs.vscoveragexml.reportsPaths property to the command? See [Coverage & Test Data] Generate Reports for C#, VB.net .

Hi @Andrei_Epure

Thanks for the reply. Upon investigation, it was not an issue with the exceptions themselves but a configuration issue on our end.

We have two test projects, Tests.Unit and Tests.Integration, and the pipeline was only providing the trx and coverage files for the Tests.Integration project, which is why the coverage was not as expected.

This has now been resolved. Thank you for your support in any case.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.