Search code examples
c#moqcastle-dynamicproxy

Moq Comparison is inconsistent


I'm using the Moq framework for mocking. I have found an issue with the Equals override not working as expected. It seems that there must be an override in the dynamic object that always returns false. Here is some sample code. I'm using Moq version 4.2.1507.0118 from nuget.

public class B
{
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var a = new Moq.Mock<B>().Object;
        var b = a;
        bool equalsOperator = a == b; //returns true
        bool referenceEquals = object.ReferenceEquals(a, b); //returns true
        bool equals_b = a.Equals(b); //returns false
        bool equals_a = a.Equals(a); //returns false
    }
}

The other interesting thing is if a breakpoint is placed on the Equals override, it is never hit. Is there a bug in the Moq framework, or is there something I'm doing wrong?


Solution

  • To fix this you have to set the CallBase property of moq to true, setting that will make sure you are calling the base implementation or its overridden method.

    var a = new Moq.Mock<B>().Object;
    

    Change this to

    var a = new Moq.Mock<B>() { CallBase = true }.Object;
    

    From the Moq Quickstart (emphasis added):

    Make mock behave like a "true Mock", raising exceptions for anything that doesn't have a corresponding expectation: in Moq slang a "Strict" mock; default behavior is "Loose" mock, which never throws and returns default values or empty arrays, enumerables, etc. if no expectation is set for a member

    Thus, you're getting false, the default value for a bool.