vendredi 26 août 2016

Best approach at writing mock on methods where Expression

I'm writing some unit tests for my methods which gets data from a database. The data access portion is encapsulated in IRepository and I have the following class which is fairly straight forward:

interface IRepository<T> 
{
    T GetFirst(Expression<Func<T, bool>> predicate);
}

Where the implementation of GetFirst is a simple FirstOrDetault

public T GetFirst(Expression<Func<T, bool>> predicate)
{
    return this.Entities.FirstOrDefault(predicate);
}

The actual class/method which I am testing is as follows:

public class SimpleClass
{
     private Repository<Home> repo = new Repository<Home>();

     public Home GetHome(int id) 
     {
          return repo.GetFirst(c => c.id == id);
     }  
}

The thing is, in the test class I have managed to get a valid mock response by using either of the following:

_homeMoq.Setup(x => x.GetFirst(It.IsAny<Expression<Func<Home, bool>>>())).Returns(customHomeEntity);

or

_homeMoq.Setup(x => x.GetFirst(It.IsAny<Expression<Func<Home, bool>>>())).Returns((Expression<Func<Home, bool>> predicate) => customHomeEntities.FirstOrDefault(predicate));

I prefer to use the second approach as it doesn't use "It.IsAny" but I was wondering if there is a cleaner way (or better) to write it?

Thank you all for any input given.

Aucun commentaire:

Enregistrer un commentaire