I have a Class Library, it contains the following Model and Method
Model:
public class Employee {
public int EmpId { get; set; }
public string Name { get; set; }
}
Method:
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();
}
}
I have a Test Method
[TestMethod()]
public void GetEmployeeTest() {
EmployeeService obj = new EmployeeService();
var result = obj.GetEmployee();
Xunit.Assert.Collection<Employee>(result, m => Xunit.Assert.Contains("John",m.Name));
}
I got an Exception message
Assert.Collection() Failure
Collection: [Employee { EmpId = 1, Name = "John" }, Employee { EmpId = 2, Name = "Albert John" }]
Expected item count: 1
Actual item count: 2
My requirement is to check all the items.Name
should contain the sub string "John". Kindly assist me how to check using Xunit.Assert.Collection
It appears that Assert.Collection only uses each element inspector once. So, for your test, the following works:
If the sequence result
has exactly two elements:
[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));
}
If there are many elements, changing the Assert
to
Assert.All(result, item => Assert.Contains("John", item.Name));
should give you the result you are expecting.