Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Verify is not capturing a classes state at the time of invocation. #1118

Closed
djseng opened this issue Dec 15, 2020 · 1 comment
Closed

Verify is not capturing a classes state at the time of invocation. #1118

djseng opened this issue Dec 15, 2020 · 1 comment

Comments

@djseng
Copy link

djseng commented Dec 15, 2020

I expect this test to pass:

    [TestClass]
    public class IsThisABug
    {
        [TestMethod]
        public void SaverSavesTwice()
        {
            var mock = new Mock<ISaver>();
            var saver = mock.Object;
            var thing = new Thing { Value = "A" };

            saver.Save(thing);

            thing.Value = "B";

            saver.Save(thing);

            mock.Verify(s => s.Save(It.Is<Thing>(t => t.Value == "A")));
            mock.Verify(s => s.Save(It.Is<Thing>(t => t.Value == "B")));
        }

        public interface ISaver
        {
            long Save(Thing thing);
        }

        public class Thing
        {
            public string Value { get; set; }
        }
    }

The first Verify call fails, output says that Value == "B" was executed twice.

@stakx
Copy link
Contributor

stakx commented Dec 15, 2020

This is by design. Moq observes the usual .NET equality rules (object.Equals), so by default, reference types are compared by reference/identity. You can either turn your type into a struct, C# 9+ record, or use a custom Capture matcher to inspect/copy state at the time of invocation.

@stakx stakx closed this as completed Dec 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants