d0001
d0001

Reputation: 2190

Moq return value for object using Mock.of?

I need to mock the return value of a method in an object. I have something like this:

var mock = Mock.Of<IExample>( x => x.GetAll() == new List<IOtherExample>()) ;

but I get an error. If I use GetAll as property instead it works:

var mock = Mock.Of<IExample>( x => x.GetAll == new List<IOtherExample>()) ;

I know I can do this using new Mock, Setup and Return like this:

mock.Setup(x => x.GetAll()).Returns(new List<IOtherExample>());

but I would like to learn how to do this using Mock.Of.

The error looks something like this:

 Expression of type 'System.Collections.Generic.List' cannot be used for parameter of type 'System.Collections.Generic.IList' of method 'Moq.Language.Flow.IReturnsResult' Returns(System.Collections.Generic.IList)'

Again keep in mind that it works if GetAll is a property.

Thank you.

public interface IExample : IGenericExample<IOtherExample>
{

}

public interface IGenericExample<T>
{
   IList<T> GetAll()
}

Upvotes: 2

Views: 3031

Answers (2)

Isioma Nnodum
Isioma Nnodum

Reputation: 1318

var example = Mock.Of<IExample>();
Mock.Get(example).Setup(x => x.GetAll()).Returns(new List<IOtherExample>());

That said, I think Mock.Of<> is a little semantically backwards. It communicates that the returned object has a mock compared to new Mock<> which returns an mock object that has a real instance.

I find this setup to be more meaningful than the snippet above.

var exampleMock = new Mock<IExample>();
exampleMock.Setup(x => x.GetAll()).Returns(new List<IOtherExample>());

Later, when the instance is needed to pass as an argument or for an assertion, using exampleMock.Object is simple enough.

Upvotes: 1

PermaFrost
PermaFrost

Reputation: 1446

Can't post this as a comment due to code formatting:

void Main()
{   
    var t = Mock.Of<IExample>(x => x.GetAll() == new List<IOtherExample>());
    t.GetAll().Dump();
}

// Define other methods and classes here
public interface IOtherExample
{
}

public interface IExample : IGenericExample<IOtherExample>
{

}

public interface IGenericExample<T>
{
   IList<T> GetAll();
}

This works in my LINQPad, I'm using Moq 4.0. Am I missing something?

Upvotes: 2

Related Questions