将接口模拟为多种类型

Mocking up an Interface as more than one types

为什么这段代码不起作用?

var channelsList = new List<IChannel>
{
    Mock.Of<IChannel>(m => m == new ChannelOne()),
    Mock.Of<IChannel>(m => m == new ChannelTwo()),
};

假设IChannel定义为:

public interface IChannel
{
    int DoWork();
    int DoOtherWork();
}

然后您可以使用 Moq.Linq 定义不同的行为,如下所示:

var channelsList = new List<IChannel>
{
    Mock.Of<IChannel>(m => m.DoWork() == 1 && m.DoOtherWork() == 1),
    Mock.Of<IChannel>(m => m.DoWork() == 2)
};

Assert.Equal(1, channelsList.First().DoWork());
Assert.Equal(2, channelsList.Last().DoWork());

但是有一个限制,例如您不能设置 Throws...


LINQ to Mocks is great for quickly stubbing out dependencies that typically don't need further verification. If you do need to verify later some invocation on those mocks, you can easily retrieve them with Mock.Get(instance).

注意:强调我的

LINQ to Mocks.