gpt4 book ai didi

c# - 如何使用 FluentAssertions 断言属性的默认值?

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:59 26 4
gpt4 key购买 nike

我有一个包含各种类型的字段/属性等的类:

public string SomeStringData;
public int? SomeNullableIntegerData;
public SomeDataClass SomeSpecificData;
public int SomeIntegerData;

在我的部分代码中,只有 SomeStringData 应该被填充,我想明确地测试它。我用 FluentAssertions并且有

actual.SomeStringData.Should().Be("Whatever");

但是如何测试,没有其他元素没有被触及并且仍然有它们的默认值?我当然可以:

actual.SomeNullableIntegerData.Should().NotHaveValue("Must have no value.");
actual.SomeDataClass.Should().BeNull("Must have no value.");
actual.SomeNullableIntegerData.Should().Be(0, "Must have no value.");

但是,如何更明确地表达这些项应该有默认值呢?

例如,使用一个虚构的 BeDefault 运算符:

actual.SomeNullableIntegerData.Should().BeDefault("Must have no value.");
actual.SomeDataClass.Should().BeDefault("Must have no value.");
actual.SomeNullableIntegerData.Should().BeDefault("Must have no value.");

有这样的选择吗?

最佳答案

我会创建扩展方法

public static void ShouldHaveDefaultValue<T>(this T value)
{
if (!EqualityComparer<T>.Default.Equals(value, default(T)))
throw new AssertionException("Must have default value.");
}

用法:

actual.SomeNullableIntegerData.ShouldHaveDefaultValue();
actual.SomeDataClass.ShouldHaveDefaultValue();
actual.SomeIntegerData.ShouldHaveDefaultValue();

BeDefault() 扩展 Should() 会很困难,因为有不同的 Should() 扩展返回不同的断言对象 - BooleanAssertionsStringAssertionsGuidAssertions 等。所有这些断言类都没有您可以扩展的公共(public)基类。

关于c# - 如何使用 FluentAssertions 断言属性的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com