我正在尝试将类型自定义类的字典检查为值。
我想知道我在Dictionary中搜索值的方法是否正确使用Fluent Assertion中的ContainValue。
这是代码
public static void VerifyDictionary()
{
try
{
Dictionary<int, Employee> empDict = new Dictionary<int, Employee>
{
{ 1, new Employee() {EmployeeID = 100,Name="Karthik", EmployeeEmail="karthik@executeautomation.com", EmployeeAddress="Chennai,India"}},
{2, new Employee() { EmployeeID = 101,Name="Jack",EmployeeEmail="Jack@jill.com",EmployeeAddress="CA"} },
{3, new Employee() { EmployeeID=102,Name="Sam",EmployeeEmail="Sam@sung.com",EmployeeAddress="SFO"}},
{4, new Employee() { EmployeeID=103,Name="Max",EmployeeEmail="micro@max.com",EmployeeAddress="India" }}
};
empDict.Should().ContainValue(new Employee() { EmployeeID = 10, EmployeeEmail = "micro@max.com", EmployeeAddress = "India", Name = "Max" }, "because thats the information I need");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
员工类
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string EmployeeEmail { get; set; }
public string EmployeeAddress { get; set; }
}
当我执行此代码时,我显示异常,如图所示
**
Expected dictionary {[1, BDDDemo.Employee], [2, BDDDemo.Employee], [3, BDDDemo.Employee], [4, BDDDemo.Employee]} to contain value
BDDDemo.Employee
{
EmployeeAddress = "India"
EmployeeEmail = "micro@max.com"
EmployeeID = 10
Name = "Max"
} because thats the information I need.
**
请帮助我理解我在这里做错了什么。
谢谢,
答案 0 :(得分:1)
ContainValue
检查值是否在字典中是基于字典中值Equals
的方法。
在这种情况下,Employee
不会覆盖Equals
,因此使用从Object继承的实现;将使用参考相等。
例如,以下代码将通过:
var expected = new Employee { EmployeeID = 10 };
var dictionary = new Dictionary<int, Employee> { {1, expected} };
dictionary.Should().ContainValue( expected );
然而,这会失败,因为它们是Employee
的两个不同实例,即使它们的所有成员都是相同的:
var expected = new Employee { EmployeeID = 10 };
var dictionary = new Dictionary<int, Employee> { {1, expected} };
dictionary.Should().ContainValue( new Employee { EmployeeID = 10 } );
要使此后续案例通过,您可以覆盖Equals
。但是,整个类是可变的,所以我不能推荐这个,除非你也使用你用来确定Equality不可变的任何成员。
如果不修改课程,最好的办法是使用不同的断言,可能就是这样:
dictionary.Values.Should().Contain(employee =>
/* Logic for how you want to determine a match */);