我有以下功能,其中包含正在测试的步骤和类。当我将名称字段可见性更改为公共时,我可以在Table.CreateInstance<>()
后检索值,但是当将其设为私有时,它会失败。
方案:获取员工详细信息。
Given below employee create a user.
| Name | age |
| John | 28 |
法典
[Binding]
public class TableSteps
{
[Given(@"below employee create a user.")]
public void GivenBelowEmployeeCreateAUser_(Table table)
{
Employee employee = table.CreateInstance<Employee>();
Console.Write("Name:" + employee.Name); //Works as it is public.
Console.Write("Name:"+ employee.EmpName); //No value returned here. Just null.
}
}
public class Employee
{
private string Name { get; set; } //not working.
//public string Name { get; set; } //works.
public int age { get; set; }
public Employee(String Name, int age)
{
this.Name = Name;
this.age = age;
}
public string EmpName
{
get { return Name; }
}
}
CreateInstance 只会设置公共值,因为它是它所能访问的全部。
像这样:
[Binding]
public class TableSteps
{
[Given(@"below employee create a user.")]
public void GivenBelowEmployeeCreateAUser_(Table table)
{
Employee employee = new Employee(table.Rows[0][0], int.Parse(table.Rows[0][1]));
Console.Write("Name:" + employee.Name); //Works as it is public.
Console.Write("Name:"+ employee.EmpName); //No value returned here. Just null.
}
}
如果你想让它更具可读性,你可以把它包装到一个扩展方法中,比如。
Employee employee = table.CreateEmployee();
但是如果你想要一个通用的解决方案,那么你必须自己写一个。
不过,这应该不会太难,只需创建一个像 CreateInstance
这样的扩展方法,该方法接受对象的参数数组,然后反映您正在创建的类型的构造函数,以找到具有与调用该方法相同数量的参数的构造函数,并使用传递的参数调用该构造函数。
如果这些类仅用于测试,我会将它们公开,因为这是最简单的解决方案。
这类似于 SpecFlow 和复杂对象,因为您可以创建一个类作为 SpecFlow 表的"视图模型":
public class EmployeeRow
{
public string Name { get; set; }
public int Age { get; set; }
public Employee ToEmployee()
{
return new Employee(Name, Age);
}
}
然后在步骤定义中:
[Given(@"below employee create a user.")]
public void GivenBelowEmployeeCreateAUser_(Table table)
{
Employee employee = table.CreateInstance<EmployeeRow>().ToEmployee();
Console.Write("Name:" + employee.Name);
Console.Write("Name:"+ employee.EmpName);
}