Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Moq methods that return "this"

I have an interface

interface IService
{
    IService Configure();
    bool Run();
}

The "real" implementation does this:

class RealService : IService
{
    public IService Configure()
    {
        return this;
    }

    public bool Run()
    {
        return true;
    }
}

Using Moq to mock the service creates a default implementation of Configure() that returns null.

Is there a way to setup methods in Moq that return the mocked instance?

like image 944
Joe Enzminger Avatar asked Oct 18 '16 18:10

Joe Enzminger


1 Answers

Assuming that you are using Moq, you can simply Setup the mock to return itself:

var mock = new Mock<IService>();

mock.Setup(service => service.Configure()).Returns(mock.Object);

var testClass = new TestClass(mock.Object);

Then validate if the method returned what you expect:

Assert.AreEqual(mock.Object, testClass.DoStuff());
like image 94
meJustAndrew Avatar answered Sep 19 '22 03:09

meJustAndrew