我刚刚把很多项目升级到to 2015/C#6。
现在,MSTest的代码覆盖率分析报告说,一些汽车属性没有包含在单元测试中。Visual 2013的情况并非如此,我怀疑这可能与C#6中的新的自动属性特性有关。
处理所有的错误-阳性,这产生了相当违背的目的代码覆盖工具,因为它使它几乎不可能确定实际的代码,缺乏测试覆盖率。我们不想为所有的DTO编写单元测试,而且我真的不想使用ExcludeFromCodeCoverage对每个自动属性进行注释的项目。
我在https://github.com/iaingalloway/VisualStudioCodeCoverageIssue创建了一个工作的MCVE
VisualStudio2013.sln。VisualStudio2015.sln。是否可以将Visual 2015中内置的代码覆盖工具配置为忽略像Visual 2013这样的自动属性?
发布于 2015-09-03 14:23:56
作为解决办法,您可以将以下内容添加到.runsettings文件中:
<RunSettings>
<DataCollectionRunSettings>
<DataCollector ...>
<Configuration>
<CodeCoverage>
<Functions>
<Exclude>
<Function>.*get_.*</Function>
<Function>.*set_.*</Function>
</Exclude>
...这不是一个很好的解决办法,但只要您没有使用任何名称中包含"get_“或"set_”的函数,它就会使您获得所需的行为。
发布于 2017-09-12 19:17:48
我不喜欢过滤所有get/set方法,特别是因为我有时编写需要测试的get和set逻辑。对我来说,对于相对简单的模型的基本内容,下面的两个xUnit测试运行得很好:
public class ModelsGetSetTest
{
[ClassData(typeof(ModelTestDataGenerator))]
[Theory]
public void GettersGetWithoutError<T>(T model)
{
var properties =
typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
for (var i = 0; i < properties.Length; i++)
{
var prop = properties[i];
if (prop.GetGetMethod(true) != null)
prop.GetValue(model);
}
}
[ClassData(typeof(ModelTestDataGenerator))]
[Theory]
public void SettersSetWithoutError<T>(T model)
{
var properties =
typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
for (var i = 0; i < properties.Length; i++)
{
var prop = properties[i];
if (prop.GetSetMethod(true) != null)
prop.SetValue(model, null);
}
}
public class ModelTestDataGenerator : IEnumerable<object[]>
{
private readonly List<object[]> _data = new List<object[]>();
public ModelTestDataGenerator()
{
var assembly = typeof(Program).Assembly;
var nsprefix = $"{typeof(Program).Namespace}.{nameof(Models)}";
var modelTypes = assembly.GetTypes()
.Where(t => t.IsClass && !t.IsGenericType) // can instantiate without much hubbub
.Where(t => t.Namespace.StartsWith(nsprefix)) // is a model
.Where(t => t.GetConstructor(Type.EmptyTypes) != null) // has parameterless constructor
.ToList();
foreach (var modelType in modelTypes) _data.Add(new[] {Activator.CreateInstance(modelType)});
}
public IEnumerator<object[]> GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}更新的2020-03-18:这个版本使用反射来查找特定命名空间下的模型。
发布于 2015-09-01 16:03:48
我认为[ExcludeFromCodeCoverage]是你唯一的选择。这只是你不得不做的一件事。我个人确实在属性getter/getter上编写了单元测试,特别是在WPF中,我想确保发生了属性更改通知。
https://stackoverflow.com/questions/32329430
复制相似问题