-
Hi there, we switched to fluent assertion since there are a lot of advantages with that library. thanks for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hoe about comparing with an anonymous object? |
Beta Was this translation helpful? Give feedback.
-
[Fact]
public void Different_instances()
{
// Arrange
var subject = new A { ReferenceType = "", B = new B { PrimitiveType = 42, ValueType = default(Guid) } };
var clone = new A { ReferenceType = "", B = new B { PrimitiveType = 42, ValueType = default(Guid) } };
// Act / Assert
subject.Should().BeEquivalentTo(clone, opt => opt
.Using(new NotSameEqquivalencyStep()));
}
[Fact]
public void Same_nested_instance()
{
// Arrange
B b = new B { PrimitiveType = 42, ValueType = default(Guid) };
var subject = new A { ReferenceType = "", B = b };
var clone = new A { ReferenceType = "", B = b };
// Act / Assert
subject.Should().NotBeEquivalentTo(clone, opt => opt
.Using(new NotSameEqquivalencyStep()));
}
[Fact]
public void Same_root_instance()
{
// Arrange
var subject = new A { ReferenceType = "", B = new B { PrimitiveType = 42, ValueType = default(Guid) } };
var clone = subject;
// Act / Assert
subject.Should().NotBeEquivalentTo(clone, opt => opt
.Using(new NotSameEqquivalencyStep()));
}
private class NotSameEqquivalencyStep : IEquivalencyStep
{
public EquivalencyResult Handle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator)
{
if (comparands.Subject is null || comparands.Expectation is null)
{
// I guess both being null is okay.
return EquivalencyResult.ContinueWithNext;
}
if (comparands.RuntimeType.IsValueType || comparands.RuntimeType == typeof(string))
{
return EquivalencyResult.ContinueWithNext;
}
bool suceeded = Execute.Assertion
.ForCondition(!ReferenceEquals(comparands.Subject, comparands.Expectation))
.BecauseOf(context.Reason)
.FailWith("Subject and Expectation should not reference the same instance in memory.");
return suceeded
? EquivalencyResult.ContinueWithNext
: EquivalencyResult.AssertionCompleted;
}
}
private class A
{
public string ReferenceType { get; set; }
public B B { get; set; }
}
private class B
{
public int PrimitiveType { get; set; }
public Guid ValueType { get; set; }
} |
Beta Was this translation helpful? Give feedback.
IEquivalencyStep
is what you're looking for.All user-registered
equivalencyStep
s are run before the built-in, so we can guard against referential equality there.