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

Mock.Verify susceptible to reference type alterations #1187

Closed
marnu123 opened this issue Jul 21, 2021 · 3 comments
Closed

Mock.Verify susceptible to reference type alterations #1187

marnu123 opened this issue Jul 21, 2021 · 3 comments

Comments

@marnu123
Copy link

marnu123 commented Jul 21, 2021

Hello!

Firstly, great tool! It's really helped me a lot so far, and I never go a day without it.

Summary:
When using reference types as parameters to mocked methods, and altering internal variables of parameter, calling Mock.Verify on the method can fail, because Mock stores the reference to the parameter, and not a copy of it.

Code setup:

private class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

public interface IApi
{
    void Add(object obj);
}

[Fact]
public void Test()
{
    var obj = new Person() {Name = "Name", Surname = "Surname"};
    var mock = new Mock<IApi>();
    var mockedObject = mock.Object;
    mockedObject.Add(obj);

    obj.Name = "Shaun";
    
    // Name, in this case is equal to "Shaun"
    // Verification fails because the "Name" properties differ
    mock.Verify(e => e.Add(new Person() {Name = "Name", Surname = "Surname"}), Times.Once);
}

Expected outcome:
The verification should succeed, even though the object changed. I expect that the parameters that were passed be deep cloned to be used for verification

Current outcome:
Verification fails

Moq version: 4.16.1

@stakx
Copy link
Contributor

stakx commented Jul 21, 2021

We get this report all the time. I'll let you use the search facility to find similar issues (along with my responses), I'll just say here that this behavior is by design (the usual .NET equality semantics apply) and it won't be changed.

@stakx stakx closed this as completed Jul 21, 2021
@marnu123
Copy link
Author

Perfect, thanks! Then I know what to do. I see one similar "issue" was reported and closed recently, so sorry about that. I'm not used to Github's structure yet, coming from an Azure DevOps background

@stakx
Copy link
Contributor

stakx commented Dec 31, 2022

If anyone finds this issue and is experiencing the same problem, please see #1319; the last code example in the PR description shows a way how to solve this.

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