我有以下功能,包括测试中的步骤和类。当我将名称字段可见性更改为公共时,我可以在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; }
}
}
答案 0 :(得分:1)
CreateInstance只会设置公共值,因为它可以访问它。
答案 1 :(得分:0)
Like this:
[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.
}
}
you could wrap this into an extension method if you want to have it a bit more readable, something like.
Employee employee = table.CreateEmployee();
but if you want a generic solution then you'll have to write one your self.
it shouldn't be too hard though, just create an extension method like CreateInstance
that takes a param array of objects, and then reflect over the constructors of the type you are creating to find the constructor which has the same number of params as the method was invoked with and invoke that constructor using the passed parameters.
If these classes are just for testing I would make them public though as this is the easiest solution.
答案 2 :(得分:0)
这类似于SpecFlow and complex objects,因为您可以创建一个充当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);
}