Joe Enzminger
Joe Enzminger

Reputation: 11190

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?

Upvotes: 8

Views: 3310

Answers (3)

meJustAndrew
meJustAndrew

Reputation: 6603

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());

Upvotes: 5

Nkosi
Nkosi

Reputation: 246998

Either way will work to setup methods that return the mocked instance.

//Arrange
var instance = Mock.Of<IService>();//mocked instance
var mockService = Mock.Get(instance);//mock object used to setup instance functionality
//setup method to return mocked instance
mockService.Setup(m => m.Configure()).Returns(instance);

Or

//Arrange
var mockService = new Mock<IService>();//mock object used to setup instance functionality
var instance = mockService.Object;//mocked instance
//setup method to return mocked instance
mockService.Setup(m => m.Configure()).Returns(instance);

Upvotes: 3

TheRock
TheRock

Reputation: 1541

You can just create another Mock Object that uses the same interface and return it:

[TestClass]
public class UnitTest1
{

    [TestMethod]
    public void TestMethod1()
    {
        var serviceMock1 = new Mock<IService>();
        var serviceMock2 = new Mock<IService>();

        serviceMock1.Setup(service => service.Configure())
            .Returns(serviceMock2.Object);

        var testClass = new TestClass(serviceMock1.Object);

        Assert.IsNotNull(testClass.DoStuff());
    }
}

public class TestClass
{
    private readonly IService _service;

    public TestClass(IService service)
    {
        _service = service;
    }

    public IService DoStuff()
    {
        return _service.Configure();
    }
}


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

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

    public bool Run()
    {
        return true;
    }
}

Upvotes: 2

Related Questions