Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble Mocking Lambda withing Unitofwork's Repository

I'm using .net 4 with C#, EntityFramework 4, and Moq 4. I'm attempting to mock my UnitOfWork, a Repository, and finally a method call.

Here is the code I am having trouble with

        var unitOfWorkMock = new Mock<UnitOfWork>();
        var cFieldRepositoryMock = new Mock<IRepository<CField>>();

        System.Linq.Expressions.Expression<Func<CField, bool>> query = (x) => x.CID == c && x.FID == parentFID;

        cFieldRepositoryMock.Setup(x => x.GetFirst(query));

The Method Signature for GetFirst:

          T GetFirst(Expression<Func<T, bool>> query = null,
        Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null);

CField:

public class CField
{
    public CField()
    {
       //do stuff
    }
    public int ID { get; set; }
    public int FID { get; set; }
    public int CID { get; set; }
}

What I expect to happen: I am expecting that wheh I call my cFieldRepositoryMock's GetFirst method, it will match the lambda expression I pass in against the expression I defined in the Setup.

What's Happening: I'm getting a compiler error on the Setup assignment: "An Expression tree may not contain a call or invocation that uses optional arguments"

I am clearly doing something wrong, I'm just not sure what. Any advice is appreciated, I am fairly new to unit testing.

Thanks! AFrieze

like image 376
AFrieze Avatar asked Sep 19 '11 16:09

AFrieze


1 Answers

The eror you're receiving seems to be actually a limitation of expressions:

To unittest stuff like this consider to use It.IsAny ( as Carsten already suggested ):

cFieldRepositoryMock.Setup(x => x.GetFirst(query, It.IsAny<Func<IQueryable<CField>, IOrderedQueryable<CField>>>()));
like image 76
David Avatar answered Oct 22 '22 05:10

David