c# - Xunit.Assert.Collection 中的问题 - C#

标签 c# unit-testing collections assert xunit

我有一个类库,它包含以下模型和方法

型号:

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/

相关文章:

c# - 如何在 Xamarin 中测试共享代码

c# - 在 C# 中序列化和反序列化表达式树

java - 列表和 map 的通用集合?

c# - ServiceStack MVC 3+ 示例

c# - 在没有 TriggeredSend 的情况下向单个 ExactTarget 订阅者发送电子邮件

unit-testing - 如何使用 MS Fakes 为索引属性创建 stub

unit-testing - 报告单元测试结果

unit-testing - 为什么在单击 Resharper "Run all tests"按钮与使用键盘快捷键命令时会出现不同的行为?

ruby-on-rails - collection_select 给出 ActiveRecord::AssociationTypeMismatch

Magento - 反转集合的最佳方式