19

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?

Cristian Diaconescu
  • 34,633
  • 32
  • 143
  • 233
  • 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](https://learn.microsoft.com/en-us/dotnet/api/nunit.framework.assert.referenceequals?view=xamarin-ios-sdk-12) to discourage people from using it. – Tony Edgecombe Dec 17 '21 at 07:37

2 Answers2

23

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.

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • 1
    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! – Cristian Diaconescu Jul 19 '13 at 09:01
  • 4
    That's the big difference between (Not)BeSameAs() and (Not)Be. The former uses reference equality, the latter object.Equals(). – Dennis Doomen Jul 19 '13 at 13:07
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
chris31389
  • 8,414
  • 7
  • 55
  • 66