我有一个类库,它包含以下模型和方法
型号:
public class Employee {
public int EmpId { get; set; }
public string Name { get; set; }
}
方法:
public class EmployeeService {
public List<Employee> GetEmployee() {
return new List<Employee>() {
new Employee() { EmpId = 1, Name = "John" },
new Employee() { EmpId = 2, Name = "Albert John" },
new Employee() { EmpId = 3, Name = "Emma" },
}.Where(m => m.Name.Contains("John")).ToList();
}
}
我有一个测试方法
[TestMethod()]
public void GetEmployeeTest() {
EmployeeService obj = new EmployeeService();
var result = obj.GetEmployee();
Xunit.Assert.Collection<Employee>(result, m => Xunit.Assert.Contains("John",m.Name));
}
我收到一条异常消息
Assert.Collection() Failure
Collection: [Employee { EmpId = 1, Name = "John" }, Employee { EmpId = 2, Name = "Albert John" }]
Expected item count: 1
Actual item count: 2
我的要求是检查所有 items.Name
是否应该包含子字符串“John”。请协助我如何检查使用 Xunit.Assert.Collection
最佳答案
似乎 Assert.Collection 只使用每个元素检查器一次。因此,对于您的测试,以下工作:
如果序列 result
恰好有两个元素:
[Fact]
public void GetEmployeeTest()
{
EmployeeService obj = new EmployeeService();
var result = obj.GetEmployee();
Assert.Collection(result, item => Assert.Contains("John", item.Name),
item => Assert.Contains("John", item.Name));
}
如果有很多元素,将Assert
改为
Assert.All(result, item => Assert.Contains("John", item.Name));
应该给你你期望的结果。
关于c# - Xunit.Assert.Collection 中的问题 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43874305/