Dictionary<string, string[]> ShouldContainKeyAndValue 尽管找到了预期值但单元测试失败

Dictionary<string, string[]> ShouldContainKeyAndValue fails unit test despite finding the expected value

我使用 XUnit 和 Shouldly 编写了这个单元测试。请注意,我替换了部分命名空间、变量名、属性等,因为客户是一个大型 public 组织。

[Fact]
public async void ValidateCreateXXXX_InvalidIdVersionAndStatus_Should_Fail()
{
    // Arrange
    var XXXX = new XXXX.Microservices.XXXX.Models.XXXX
    {
        Id = 1,
        CreatedDateTime = DateTime.Now,
        CreatedBy = "Test",
        UpdatedDateTime = DateTime.Now,
        UpdatedBy = "Test",
        KlientId = 1,
        Version = 0,
        Status = XXXXStatus.Oprettet
    };
    var sut = new XXXXBusinessRule();

    // Act
    var result = await sut.ValidateCreateXXXX(XXXX);

    // Assert
    result.IsSuccess.ShouldBeFalse();
    result.ResultType.ShouldBe(ResultType.Invalid);
    ((Dictionary<string, string[]>)result.Data).ShouldContainKeyAndValue("Id", new []{ "'Id' must be equal to '0'." });
}

所以问题是我的测试失败并显示以下消息:

Shouldly.ShouldAssertException : (Dictionary<string, string[]>)result.Data
should contain key
"Id"
    with value
["'Id' must be equal to '0'."]
    but value was
["'Id' must be equal to '0'."]
   at 

XXXX.Unit.BusinessRule.XXXXBusinessRuleTests.ValidateCreateXXXX_InvalidIdVersionAndStatus_Should_Fail() in C:\Source\XXXX\XXXX-udvikling\Test\XXXX.Unit\BusinessRule\XXXXBusinessRuleTests.cs:line 60
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__139_0(Object state)

请注意,预期值和实际值完全相同。这里到底发生了什么?这个错误对我来说意义不大。我也尝试过使用有效的 ShouldContainKey("Id") 。所以问题一定是字符串数组?

谁能帮我弄清楚我做错了什么?感谢所有帮助。

您可以通过以下断言实现同样的效果:

var errors = result.Data.ShouldBeAssignableTo<Dictionary<string, string[]>>();

errors.ShouldContainKey("Id");

errors["Id"].ShouldBe(new[] { "'Id' must be equal to '0'."})
  1. 除了显式转换 result.Data,您还可以使用 ShouldBeAssignableTo 对类型进行断言
  2. 您可以确保密钥存在 ShouldContainKey
  3. 最后您可以使用 ShouldBe
  4. 评估检索到的值