-2

Why this code doesn't work?

var channelsList = new List<IChannel>
{
    Mock.Of<IChannel>(m => m == new ChannelOne()),
    Mock.Of<IChannel>(m => m == new ChannelTwo()),
};
anatol
  • 1,680
  • 2
  • 24
  • 47
  • 1
    Because that is not how it is suppose to be used. Reference [LINQ to Mocks](https://github.com/Moq/moq4/wiki/Quickstart#linq-to-mocks). What are you actually trying to achieve?This might be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Nkosi Apr 25 '19 at 16:18
  • I'm trying to decorate DI `IEnumerable` – anatol Apr 25 '19 at 16:19
  • @anatol Could you share `IChannel` interface, and what mean different imlementation which method should be different? – Johnny Apr 25 '19 at 16:25

1 Answers1

2

Assuming that IChannel is defined as:

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

Then you could define different behavior using Moq.Linq like this:

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

There is however limitation that you cannot setup Throws for example...


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).

note:emphasis mine

LINQ to Mocks.

Johnny
  • 8,939
  • 2
  • 28
  • 33
  • 1
    @anatol no worries. happens to all of us. That is why we have SO to reference when we forget. Happy coding. – Nkosi Apr 25 '19 at 16:36