简体   繁体   中英

Moq - How to setup a Lazy interface

I want to mock a Lazy Interface and also Setup a method to return false.

The problem is, when i run the test, I get a NotSupportedException:

System.NotSupportedException: 'Invalid setup on a non-virtual (overridable in VB) member: mock => mock.Value

Here is a simplified example:

[TestMethod]
public void SomeTestMethod()
{
    var someService = new Mock<Lazy<IService>>();

    /*this line throws the exception*/  
    someService.Setup(x => x.Value.SomeMethod()).Returns(false);
    ...
}

Please consider that SomeMethod is actually virtual, but somehow getting the lazy initialization using x.Value is not supported by Moq.

I didn't found a solution for this specific scenario but I did view some other approaches on declarations, but sadly didn't work for me.

[TestMethod]
public void SomeTestMethod()
{
    var someService = new Mock<IService>();
    var lazySomeService = new Lazy<IService>(() => someService.Object);

    //tried this but won't compile
    //lazySomeService.Setup(x => x.Value.SomeMethod()).Returns(false);
    //lazySomeService.Value.Setup(x => x.SomeMethod()).Returns(false);
    ...
}

You started on the right track with

var someService = new Mock<IService>();
var lazySomeService = new Lazy<IService>(() => someService.Object);

but the setup needs to be on the mock not the actual Lazy implementation.

someService.Setup(x => x.SomeMethod()).Returns(false);

That way when the Lazy.Value is called, it will be using the mock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM