开发者

Using Moq with Generics and Linq Expressions

I have the following generic method:

public bool Any<TEntity>(Expression<Func<TEntity, bool>> whereCondition) where TEntity : class
{
    bool result = false;
    ObjectQuery<TEntity> query = CreateObjectSet<TEntity>();

    var queryResult = query.Where(whereCondition);

    if(queryResult.Count() > 0)
        result = true;

    return result;
}

Using Moq, I mocked an instance of the class where this method resides.

Now I'd like to mock the return result of this method:

var开发者_开发技巧 mock = new Mock<ITestRepository>();
mock.Setup(foo => foo.Single<MyObject>(It.IsAny<Expression>)).Returns(new MyObject());

What am I missing with this?


I don't know if you've already been able to solve this, but you're passing the wrong type parameter to It.IsAny<>.

Your call to Setup should actually be:

mock.Setup(foo => foo.Single(It.IsAny<Expression<Func<MyObject, bool>>>()))
    .Returns(new MyObject());


If I'm understanding what you're trying to do, Single is a static/extension method that can't be mocked with Moq. Moq works by subclassing the object under test, so statics won't work. You'll have to set up the mock on your Any method (as long as your Any method isn't an extension method itself.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜