Expressions in the Mock results

A very powerful way is using expressions in the result of a Mock. Of course as an alternative you can use a callback which gives a numerable result but just using the expression by passing it as a predicate is great.

For example, a Where statement in your code. And you want the result to be the result according the given expression. Just pass it into your Mock like so:

First create a list with an object and set it with AsQueryable():

var list = new List<Entity>()
{
   new Entity()
   {
      ID = 1,
      Titel = "Titel 1"
   },
   new AliasTitelEntity()
   {
      ID = 2,
      Titel = "Titel 2"
   }
}.AsQueryable();

Then use the list into the Mock:


_mockRepository.Setup(
   m => m.Where(It.IsAny<Expression<Func<Entity, bool>>>()))
   .Returns(
      (Expression<Func<Entity, bool>> predicate) 
      => list.Where(predicate).ToList());

Geef een antwoord

Het e-mailadres wordt niet gepubliceerd.

*
*
*

Back To Top