FluentAssertions 中是否有一种方法可以避免.And
和.Which
级联的自动对象图向下钻取?
在深入分析的某些点上,我想返回到根级别并检查状态代码。
小代码示例:
Func<Task> action = async () => await this.someContext.someResponseTask;
action.Should()
.Throw<SwaggerOpenApiException<IList<ApiValidationError>>>()
.Which.Result.Should().Contain(x => x.ErrorCode == errorCode)
.Which.ErrorDetails.Should().Contain(dictionaryWithParsedErrorDetails)
// NOTE: This does not work (compile) as it operates on "ErrorDetails",
// would like to access root level exception again.
.Which.StatusCode.Should().Be(HttpStatusCode.Conflict);
显然,我可以将 await this.someContext.someResponseTask
包装到 try/catch 中,并将异常存储到变量中,但这并不是一种真正优雅的方法,尤其是在您触手可及的 FluentAssertions 中.
最佳答案
这些是我发现的 3 个解决方案,它们在处理 Exception
时可以遍历对象图的单独路径。
顺序表示测试失败时摘要的信息丰富度。因此,例如,#3 将所有内容都放入一个表达式中并不能准确告诉您失败的原因。
第一项非常准确。
1.
var exceptionAssertion = action.Should().Throw<SwaggerOpenApiException<IList<ApiValidationError>>>();
exceptionAssertion.Which.Result.Should().Contain(x => x.ErrorCode == errorCode);
exceptionAssertion.Which.StatusCode.Should().Be((int)HttpStatusCode.Conflict);
2.
// NOTE: This .Where is not LINQ, it's from FluentAssertions!
action.Should().Throw<SwaggerOpenApiException<IList<ApiValidationError>>>()
.Where(e => e.Result.Any(r => r.ErrorCode == errorCode))
.Where(e => e.StatusCode == (int)HttpStatusCode.Conflict);
3.
action.Should()
.Throw<SwaggerOpenApiException<IList<ApiValidationError>>>()
.Which.Should().Match<SwaggerOpenApiException<IList<ApiValidationError>>>(
e =>
e.Result.Any(r => r.ErrorCode == errorCode) &&
e.StatusCode == (int)HttpStatusCode.Conflict);
关于c# - 流利的断言 : How to break through drill-down of Which/And cascades?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57971394/