简体   繁体   中英

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

I wrote this unit test using XUnit and Shouldly. Please note that I replaced parts of the namespace, variable names, properties etc, as the customer is a large public organization.

[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'." });
}

So the problem is that my test fails with the following message:

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)

Please note that the expected value and the actual value are the exact same. What the heck is happening here? This error doesn't make much sense to me. I have also tried using the ShouldContainKey("Id") which works. So the problem must be the string array?

Can someone help me figure out what I'm doing wrong? All help appreciated.

You can achieve the same with the following assertions:

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

errors.ShouldContainKey("Id");

errors["Id"].ShouldBe(new[] { "'Id' must be equal to '0'."})
  1. Rather than casting the result.Data explicitly you can use the ShouldBeAssignableTo to have an assertion on the type as well
  2. You can make sure that the key is present with ShouldContainKey
  3. And finally you can assess the retrieved value with ShouldBe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM