NUnit or Fluent Assertions test for reference equality?
Asked Answered
M

2

20

I'm using NUnit 2.6.2 + Fluent Assertions 2.0.1.

I want to assert that two references do NOT point to the same object instance. I can't find a clean way to express that.

NUnit has Assert.ReferenceEquals(ref1, ref2) - but I can't find the negated assertion.

In Fluent Assertions I can't find anything to directly support this scenario.

The only way I could do it was like this:

NUnit: Assert.False(object.ReferenceEquals(ref1, ref2));

Fluent: object.ReferenceEquals(ref1, ref2).Should().BeFalse();

Both of these seem less than ideal in terms of minimal noise. Is there a better way?

Maccabees answered 19/7, 2013 at 8:47 Comment(1)
NUnit does not have Assert.ReferenceEquals(ref1, ref2). All objects have a static method ReferenceEquals, in the case of Assert it has been overloaded to fail to discourage people from using it.Giga
P
24

You can use NotBeSameAs() method:

ref1.Should().NotBeSameAs(ref2);

Its documentation says:

Asserts that an object reference refers to a different object than another object reference refers to.

Pulpy answered 19/7, 2013 at 8:52 Comment(2)
Just what I was looking for! It wasn't intuitively clear to me what [Not]BeSameAs() did, and I failed to read the description. Thanks!Maccabees
That's the big difference between (Not)BeSameAs() and (Not)Be. The former uses reference equality, the latter object.Equals().Balboa
D
5

You can use Is.Not.SameAs() with Nunit 3.x here

var x = new object();
Assert.That(x, Is.SameAs(x)); // success
Assert.That(x, Is.Not.SameAs(x)); // fail

var y = new object();
Assert.That(x, Is.SameAs(y)); // fail
Assert.That(x, Is.Not.SameAs(y)); // success
Davie answered 28/6, 2017 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.