В настоящее время, когда я запускаю анализ покрытия кода, сообщаемое покрытие составляет 90%. Дело в том, что остальные 10% — это код собственно теста!
Как я могу заставить VS игнорировать этот тестовый код и учитывать только фактический код?





Вы можете добавить файл runsettings в свой проект.
В этом файле вы можете указать имена DLL, которые необходимо исключить из покрытия кода:
<ModulePaths>
<Include>
<!-- Include all loaded .dll assemblies (but not .exe assemblies): -->
<ModulePath>.*\.dll$</ModulePath>
</Include>
<Exclude>
<!-- But exclude some assemblies: -->
<ModulePath>.*\\Fabrikam\.MyTests1\.dll$</ModulePath>
<!-- Exclude all file paths that contain "Temp": -->
<ModulePath>.*Temp.*</ModulePath>
</Exclude>
</ModulePaths>
Эта страница и Эта страница должны дать вам более подробную информацию о том, как добавить и настроить файл runsettings для модульных тестов.
Надеюсь, это поможет вам.
@Manoj_Choudhari В моем случае это не работает stackoverflow.com/questions/62710466/…
1. Вам нужно добавить файл Xml в свой тестовый проект, расширение которого должно быть .runsettings. как только вы добавите этот файл настроек запуска, скопируйте приведенный ниже фрагмент кода и вставьте его в файл настроек запуска.
2. Внутри тега пути к модулям находится тег Исключать. В этом теге вы можете указать имена DLL или имя проекта, которые необходимо исключить из покрытия кода.
3. Для тестового проекта мы должны указать имя проекта, а не его DLL. Например: Имя моего тестового проекта — Skyve.Helper.Document.Test. Поэтому я упомянул название проекта внутри тега Исключать.
<?xml version = "1.0" encoding = "utf-8"?>
<!-- File name extension must be .runsettings -->
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName = "Code Coverage" uri = "datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName = "Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<Configuration>
<CodeCoverage>
<ModulePaths>
<Include>
</Include>
<Exclude>
<ModulePath>.*CPPUnitTestFramework.*</ModulePath>
<ModulePath>.*TestAdapter.*</ModulePath>
<ModulePath>.*\moq.dll$</ModulePath>
<ModulePath>.*Skyve.Helper.Document.Test.*</ModulePath>
</Exclude>
</ModulePaths>
<!-- Match fully qualified names of functions: -->
<!-- (Use "\." to delimit namespaces in C# or Visual Basic, "::" in C++.) -->
<Functions>
<Exclude>
<Function>^Fabrikam\.UnitTest\..*</Function>
<Function>^std::.*</Function>
<Function>^ATL::.*</Function>
<Function>.*::__GetTestMethodInfo.*</Function>
<Function>^Microsoft::VisualStudio::CppCodeCoverageFramework::.*</Function>
<Function>^Microsoft::VisualStudio::CppUnitTestFramework::.*</Function>
<Function>.*get_.*</Function>
<Function>.*set_.*</Function>
<Function>.*MoveNext.*</Function>
<!--<Function>.*ValidateAVSRequestforHierarchy.*</Function>
<Function>.*FetchDistinctAddress.*</Function>-->
</Exclude>
</Functions>
<!-- Match attributes on any code element: -->
<Attributes>
<Exclude>
<!-- Don’t forget "Attribute" at the end of the name -->
<Attribute>^System.Diagnostics.DebuggerHiddenAttribute$</Attribute>
<Attribute>^System.Diagnostics.DebuggerNonUserCodeAttribute$</Attribute>
<Attribute>^System.Runtime.CompilerServices.CompilerGeneratedAttribute$</Attribute>
<Attribute>^System.CodeDom.Compiler.GeneratedCodeAttribute$</Attribute>
<Attribute>^System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute$</Attribute>
<Attribute>^NUnit.Framework.TestFixtureAttribute$</Attribute>
<Attribute>^Xunit.FactAttribute$</Attribute>
<Attribute>^Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute$</Attribute>
<!--<Attribute>^skyve.helper.Avs.Core.Proxy$</Attribute>-->
</Exclude>
</Attributes>
<!-- Match the path of the source files in which each method is defined: -->
<Sources>
<Exclude>
<Source>.*\\atlmfc\\.*</Source>
<Source>.*\\vctools\\.*</Source>
<Source>.*\/public\\sdk\\.*</Source>
<Source>.*\\microsoft sdks\\.*</Source>
<Source>.*\\vc\\include\\.*</Source>
<Source>.*\\Program.cs </Source>
<Source>.*\\Startup.cs </Source>
<Source>.*\\Filter\\.*</Source>
<Source>.*\\RouteConfig.cs </Source>
</Exclude>
</Sources>
<!-- Match the company name property in the assembly: -->
<CompanyNames>
<Exclude>
<CompanyName>.*microsoft.*</CompanyName>
</Exclude>
</CompanyNames>
<!-- Match the public key token of a signed assembly: -->
<PublicKeyTokens>
<!-- Exclude Visual Studio extensions: -->
<Exclude>
</Exclude>
</PublicKeyTokens>
<!-- We recommend you do not change the following values: -->
<UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
<AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
<CollectFromChildProcesses>True</CollectFromChildProcesses>
<CollectAspDotNet>False</CollectAspDotNet>
</CodeCoverage>
</Configuration>
</DataCollector>
</DataCollectors>
В моем случае не работает stackoverflow.com/questions/62710466/…
Запись .*\moq.dll$ должна быть либо .*moq.dll$, либо .*\\moq.dll$, потому что нет смысла экранировать символ m в регулярном выражении.
Теперь есть атрибут ExcludeFromCodeCoverage, которым можно украсить исключенный код. Я использую его с большим успехом.
Placing this attribute on a class or a structure excludes all the members of that class or structure from the collection of code coverage information.
Если вам интересно, где находится файл, перейдите в меню «Тест» -> «Настройки теста», и вы увидите там файл .runsettings. Если нет, можно создать новый по образцу в документах Microsoft здесь: docs.microsoft.com/en-us/visualstudio/test/…