Shahar Shokrani
Shahar Shokrani

Reputation: 8740

Mocking a lazy interface results in run-time exception

I'm having difficulties while trying to properly mock an arbitrary interface wrapped inside Lazy class.

I've tried:

[TestClass]
public class MyFooServiceTests
{
    private Mock<Lazy<IFoo>> _lazyFooMock = new Mock<Lazy<IFoo>>();
    private Mock<IFoo> _fooMock = new Mock<IFoo>();
    private MyFooService _service;

    [TestMethod]
    public void FooMethod_HappyPath_ShouldReturn()
    {
        //Arrange
        _fooMock
            .Setup(x => x.DoSomething())
            .Returns(1);

        _lazyFooMock
            .SetupGet(x => x.Value)
            .Returns(_fooMock.Object); // --------> Throws Exception.

        _service = new MyService(_lazyFooMock.Object);
    }
}

public interface IFoo
{
    int DoSomething();
}

public class MyFooService
{
    public MyFooService(IFoo foo) { ... }
}

Exception Message:

Unsupported expression: x => x.Value Non-overridable members (here: Lazy.get_Value) may not be used in setup / verification expressions.

Moq: 4.16.1

Upvotes: 0

Views: 469

Answers (1)

Shahar Shokrani
Shahar Shokrani

Reputation: 8740

Solved by help of others, I've dumped the _lazyFooMock and replaced it with actual Lazy: _lazyFoo, and initiated it by the help of the overload: public Lazy(Func<T> valueFactory).

private Mock<IFoo> _fooMock = new Mock<IFoo>();
private Lazy<IFoo> _lazyFoo;

private MyFooService _service;

[TestMethod]
public void FooMethod_HappyPath_ShouldReturn()
{
    //Arrange
    _fooMock
        .Setup(x => x.DoSomething())
        .Returns(1);

    _lazyFoo = new Lazy<IFoo>(() => _fooMock.Object);

    _service = new MyFooService(_lazyFoo);
}

Upvotes: 1

Related Questions