John Petrak
John Petrak

Reputation: 2928

Need help using Moq

I am having trouble mocking in my unit tests so I made a simple example to illustrate my problem. I have the following...

public class SomeClass : ISomeInterface
    {
        public int ID { get; set; }
        public string Desc { get; set; }

        public int Create(SomeClass t)
        {
            return 5;
        }

        public int Create2(string s)
        {
            return 7;
        }
    }

    public interface ISomeInterface
    {
        int Create(SomeClass t);
        int Create2(string s);
    }

Now I have two methods to test the mocked interface

    private void TestCreate()
    {
        var mocker = new Mock<ISomeInterface>();
        mocker.Setup(x => x.Create(new SomeClass())).Returns(3);
        var result = mocker.Object.Create(new SomeClass());
    }

    private void TestCreate2()
    {
        var mocker = new Mock<ISomeInterface>();
        mocker.Setup(x => x.Create2("Test")).Returns(4);
        var result = mocker.Object.Create2("Test");
    }

TestCreate2 works and returns the mocked result "4"
TestCreate however returns "0" instead of "3"

What do I need to be able to mock methods that accept custom classes as arguments and not simple int's and strings?

Upvotes: 2

Views: 173

Answers (1)

Craig Wilson
Craig Wilson

Reputation: 12624

Yeah, this is because you have setup TestCreate to return 3 when it gets the instance of SomeClass you passed in during the Setup call. However, since you new up the instance inline, then the instance passed in during the actual Create call is not the same. Either option below will fix your problem...

private void TestCreate()
{
    var mocker = new Mock<ISomeInterface>();
    mocker.Setup(x => x.Create(It.IsAny<SomeClass>())).Returns(3);
    var result = mocker.Object.Create(new SomeClass());
}

private void TestCreate()
{
    var mocker = new Mock<ISomeInterface>();
    var someClass = new SomeClass();
    mocker.Setup(x => x.Create(someClass)).Returns(3);
    var result = mocker.Object.Create(someClass);
}

Upvotes: 3

Related Questions