c# – xUnit将Trait添加到CollectionDefinition
作者:互联网
在xUnit和Visual Studio中,我想在Test Explorer中对使用[Collection(“DB”)]属性标记的测试进行分组.我只能通过[Trait(“Collection”,“DB”)]属性进行分组测试.有没有办法如何使用[Collection(“DB”)]属性为所有测试分配特定的Trait?
更新:我已添加xUnit issue #799.
解决方法:
从http://mac-blog.org.ua/xunit-category-trait/复制.
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
using XunitCategoriesSample.Traits;
namespace XunitCategoriesSample.Traits
{
public class CategoryDiscoverer : ITraitDiscoverer
{
public const string KEY = "Category";
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
var ctorArgs = traitAttribute.GetConstructorArguments().ToList();
yield return new KeyValuePair<string, string>(KEY, ctorArgs[0].ToString());
}
}
//NOTICE: Take a note that you must provide appropriate namespace here
[TraitDiscoverer("XunitCategoriesSample.Traits.CategoryDiscoverer", "XunitCategoriesSample")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CategoryAttribute : Attribute, ITraitAttribute
{
public CategoryAttribute(string category) { }
}
}
namespace XunitCategoriesSample
{
public class Class1
{
[Fact]
[Category("Jobsearcher")]
public void PassingTest()
{
Assert.Equal(4, Add(2, 2));
}
[Fact]
[Category("Employer")]
public void FailingTest()
{
Assert.Equal(5, Add(2, 2));
}
int Add(int x, int y)
{
return x + y;
}
}
}
注意您必须在TraitDiscoverer属性中提供正确的命名空间.
但是更多,让我们制作更专业的属性:
public class JobsearcherTraitDiscoverer : ITraitDiscoverer
{
public const string VALUE = "Jobsearcher";
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
yield return new KeyValuePair<string, string>(CategoryDiscoverer.KEY, VALUE);
}
}
[TraitDiscoverer("XunitCategoriesSample.Traits.JobsearcherTraitDiscoverer", "XunitCategoriesSample")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class JobsearcherTraitAttribute : Attribute, ITraitAttribute
{
public JobsearcherTraitAttribute()
{
}
}
所以从现在开始你可以输入[JobsearcherTrait]
链接:
https://github.com/xunit/xunit/issues/394 – 讨论为什么TraitAttribute被标记为密封
https://github.com/xunit/samples.xunit/tree/master/TraitExtensibility – xunit示例如何制作自定义属性
https://github.com/wespday/CategoryTraits.Xunit2 – 还有一个样本
https://github.com/xunit/xunit/blob/47fdc2669ae6aa28f6d642e202840193dfc7dbd7/test/test.xunit.execution/Common/TraitHelperTests.cs – xunit测试实现自定义属性的示例
标签:c,xunit,xunit-net 来源: https://codeday.me/bug/20190711/1431623.html