c# - C#每个属性都应该执行TestMethod
问题描述
我创建了一个自定义 xUnit 理论测试 DataAttribute,名为RoleAttribute
:
public class RoleAttribute : DataAttribute
{
public Role Role { get; set; }
public RoleAttribute(Role role, Action<Role> method)
{
Role = role;
AuthRepository.Login(role);
method(role);
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
return new[] { new object[] { Role } };
}
}
我有测试方法OpenProfilePageTest
:
public class ProfileTest : AuthTest
{
[Theory, Priority(0)]
[Role(Enums.Role.SuperUser, OpenProfilePageTest)]
[Role(Enums.Role.Editor, OpenProfilePageTest)]
public void OpenProfilePageTest(Enums.Role role)
{
var profile = GetPage<ProfilePage>();
profile.GoTo();
profile.IsAt();
}
}
我想要的是它首先执行的每个角色(属性):
AuthRepository.Login(role);
(的构造函数RoleAttribute
)
然后继续使用OpenProfilePageTest()
方法内部的代码。在它重复相同但针对第二个属性之前。
我怎样才能做到这一点,现在我正试图通过OpenProfilePageTest()
在属性内部传递方法并在其构造函数中执行它来实现这一点。必须有比传递我相信的方法更好的方法来实现这一点?
解决方案
您可以在不通过方法的情况下实现此目的,您需要稍微修改您的属性。我更改了属性以获取您要测试的所有角色并在数据中返回它们。这是一个例子
public class RolesAttribute : DataAttribute
{
private Role[] _roles;
public RolesAttribute(params Role[] roles)
{
_roles = roles;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
var data = new List<object[]>();
//We need to add each role param to the list of object[] params
//This will call the method for each role
foreach(var role in _roles)
data.Add(new object[]{role});
return data;
}
}
然后在您的测试中,您只需在一个属性中传递您想要测试的所有角色,就像这样
public class ProfileTest : AuthTest
{
[Theory, Priority(0)]
[Roles(Enums.Role.SuperUser, Enums.Role.Editor)]
public void OpenProfilePageTest(Enums.Role role)
{
AuthRepository.Login(role);
var profile = GetPage<ProfilePage>();
profile.GoTo();
profile.IsAt();
}
}
推荐阅读
- r - 功能...故障(malcoder!),包括group_by和export
- android - 此 Android 代码按什么顺序运行?
- python-3.x - 在几秒钟内获得大量数字以达到平均值、最大值和最小值时,如何转换为日期时间格式?
- express - 使用 express 设置服务器
- tensorflow - Bert 模型出现 InvalidArgumentError Condition x <= y did not hold element wise
- python - “HTTP 错误 401:未经授权”无法使用 Deta Base
- sql - Oracle SQL 性能
- android - Recyclerview 使用 Firebase 数据库删除项目错误
- mpi - 具有自动消息大小扣除的gatherv
- outlook - Salesforce for Outlook 未在 Salesforce 中显示