无法排查FluentValidation数组相关断言错误,求解决方案
待测试方法
public IEnumerable<PingOptions> MostRecentPings() { IEnumerable<PingOptions> pingOptions = new[] { new PingOptions() { DontFragment = true, Ttl = 1 }, new PingOptions() { DontFragment = true, Ttl = 1 }, new PingOptions() { DontFragment = true, Ttl = 1 }, }; return pingOptions; }
单元测试代码
[Fact] public void NetworkService_MostRecientPings_ReturnesOobject() { // Arrange var expected = new PingOptions() { DontFragment = true, Ttl = 1 }; // Act var result = _pingService.MostRecentPings(); // Assert result.Should().BeOfType<IEnumerable<PingOptions>>(); result.Should().ContainEquivalentOf(expected); result.Should().Contain(x => x.DontFragment == true); }
错误信息
NetworkUtility.Tests.PingTests.NetworkServiceTests.NetworkService_MostRecientPings_ReturnesOobject
Source: NetworkServiceTests.cs line 92
Duration: 78 msMessage:
Expected type to be System.Collections.Generic.IEnumerable`1[[System.Net.NetworkInformation.PingOptions, System.Net.Ping, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]], but found System.Net.NetworkInformation.PingOptions[].Stack Trace:
XUnit2TestFramework.Throw(String message)
TestFrameworkProvider.Throw(String message)
DefaultAssertionStrategy.HandleFailure(String message)
AssertionScope.FailWith(Func1 failReasonFunc) AssertionScope.FailWith(Func1 failReasonFunc)
AssertionScope.FailWith(String message)
TypeAssertions.Be(Type expected, String because, Object[] becauseArgs)
ReferenceTypeAssertions2.BeOfType(Type expectedType, String because, Object[] becauseArgs) ReferenceTypeAssertions2.BeOfType[T](String because, Object[] becauseArgs)
NetworkServiceTests.NetworkService_MostRecientPings_ReturnesOobject() line 107
问题原因
BeOfType<T>会严格检查对象的精确类型是否等于T。你的方法返回的是PingOptions[]数组(虽然它实现了IEnumerable<PingOptions>接口),但精确类型和接口不匹配,导致断言失败。即使把result定义为数组类型,原断言还是在检查接口类型,所以问题无法解决。
解决方案
方案1:检查是否实现目标接口(推荐)
将第一个断言替换为BeAssignableTo<T>,该方法用于验证对象是否实现了指定接口或继承了指定类型,符合方法的返回约定:
result.Should().BeAssignableTo<IEnumerable<PingOptions>>();
方案2:断言具体的数组类型
如果测试目标是确认返回的是数组类型,可直接断言数组:
result.Should().BeOfType<PingOptions[]>();
通常建议优先选择方案1,因为单元测试应关注方法的返回契约,而非具体的实现类型。
内容的提问来源于stack exchange,提问作者skmansfield

