Nick
Nick

Reputation: 6588

Func NUnit Equality Comparison

How does Equality comparison work for a Func? I have reduced the complexity of my problem to these unit tests:

[Test]
public void Will_Pass()
{
    Func<string> func = () => "key";
    Assert.That(func, Is.EqualTo(func));
}

[Test]
public void Will_Fail()
{
    Func<string> funcA = () => "key";
    Func<string> funcB = () => "key";
    Assert.That(funcA, Is.EqualTo(funcB));
}

I need to test - and successfully assert - that one instance of a Func is equal to another instance. So I basically need a way to make the Failing test pass.

Is there a way to do this without creating a custom type and overriding Equals()?

Upvotes: 3

Views: 1543

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499790

Your failing test shouldn't pass. They're not equal functions as far as anything in .NET is concerned - at least with the current Microsoft C# compiler implementation. The delegates will refer to separate generated methods (easily verified by looking at the IL.) The language specification allows them to be equal, but doesn't require it, and I don't know of any implementation that would do this.

Equality comparison for delegates basically consists of (for a single-action delegate):

  • Do the delegates refer to the same method?
  • If the delegates have targets, are those targets equal?

The first condition will be false in your test.

Upvotes: 4

Related Questions