Collection initializer code coverage

Environment:

  • ALM: Azure DevOps
  • CI system: Azure DevOps
  • Language: C# 8.0

I have a class with field collection initializers. Sonarcloud reports that the collection initializer lines are ‘Not covered by tests’.

Please recommend how to resolve this.

Sample code:

public enum ThingStatus
{
	StatusAlpha,
	StatusBeta
}
public static class ThingStatusDescription
{
	public const string StatusAlpha = "Description 1.";
	public const string StatusBeta = "Description 2.";

	private static readonly Dictionary<string, string> _statusToDescription = new Dictionary<string, string>
	{
		/* *** The following 2 lines are marked as NOT COVERED BY TESTS *** */
		{ ThingStatus.StatusAlpha.ToString(), ThingStatusDescription.StatusAlpha },
		{ ThingStatus.StatusBeta.ToString(), ThingStatusDescription.StatusBeta }
	};
	
	public static string GetDescription(string status)
	{
		if (string.IsNullOrWhiteSpace(status))
		{
			return null;
		}
		_statusToDescription.TryGetValue(status, out var description);
		return description;
	}
}

Hi,

Welcome to the community!

Do you have unit tests that cover those lines?

 
Ann

Hi Ann,
We have unit tests covering all expected GetDescription outputs. These touch all elements in the dictionary.
We do not have explicit tests covering the dictionary constructor. I don’t know how to test this collection initializer directly. Will be grateful for suggestions please!

Hey @s708

SonarQube isn’t involved in the generation of coverage reports, it only takes in the information of a report generated by another tool. I would suggest:

  • Checking the raw report you are importing into SonarCloud to see if indeed, coverage is reported as missing for these lines
  • Ask around C# developer communities / the community for your specific coverage tool for advice around whether these lines can actually be covered by tests

Makes sense. Thank you.