Reputation: 15742
I have a class with some fields/properties etc., of various types:
public string SomeStringData;
public int? SomeNullableIntegerData;
public SomeDataClass SomeSpecificData;
public int SomeIntegerData;
In part of my code, only the SomeStringData
should be filled, and I want to test explicitly that. I use FluentAssertions and have
actual.SomeStringData.Should().Be("Whatever");
But how to test, that none of the other elements are not touched and still have their default value? I could, of course:
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.");
But, how to express more clearly that these items should have the default value?
Like for example with an imaginary BeDefault
operator:
actual.SomeNullableIntegerData.Should().BeDefault("Must have no value.");
actual.SomeDataClass.Should().BeDefault("Must have no value.");
actual.SomeNullableIntegerData.Should().BeDefault("Must have no value.");
Are there such options?
Upvotes: 3
Views: 3924
Reputation: 236318
I would create extension method
public static void ShouldHaveDefaultValue<T>(this T value)
{
if (!EqualityComparer<T>.Default.Equals(value, default(T)))
throw new AssertionException("Must have default value.");
}
Usage:
actual.SomeNullableIntegerData.ShouldHaveDefaultValue();
actual.SomeDataClass.ShouldHaveDefaultValue();
actual.SomeIntegerData.ShouldHaveDefaultValue();
Extending Should()
with BeDefault()
would be difficult, because there is different Should()
extensions which return different assertions objects - BooleanAssertions
, StringAssertions
, GuidAssertions
etc. And all this assertions classes don't have common base class you would be able to extent.
Upvotes: 4
Reputation: 8909
I would just capture the previous values upfront and assert that after executing whatever is supposed to make the change, those values still have their default values. That proposed BeDefault
method can never make any assumptions about a 'default'.
Upvotes: 0