Joe Enzminger Joe Enzminger - 1 month ago 4
C# Question

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?

Answer

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