locked
unit tests: mocking methods that take linq expression RRS feed

  • Question

  • Hello,

    I'm building some unit tests and I've run into this situation that I have not encountered before. I'm trying to mock out a 

    context method like this:

                    GetMockFor<IRiskAliveContext>()
                        .Setup(ctx => ctx.ConsequencesByProject(x => x.ProjectId == 1))
                        .Returns(GetTestConsequences(1));

    The thing that I've never encountered before is the fact that ConsequencesByProject takes a linq expression. The full 

    implementation of the method looks like this:

    public static class LinqHelpers
    {
    ...
            public static IQueryable<Consequence> ConsequencesByProject(this IRiskAliveContext context,
                Expression<Func<Project, bool>> predicate)
            {
               return context.Projects.Where(predicate)
                    .SelectMany(x => x.Nodes).SelectMany(x => x.Deviations).SelectMany(x => x.Causes)
                    .SelectMany(x => x.Consequences);
            }
    ...
    }

    When my unit tests run the line above (the one that calls ConsequencesByProject(...)), it aborts the tests and quits, all tests showing failed.

    Obviously, this is not the way to mock out methods that take linq expressions. What would be the right way to do it?
    • Moved by Sabah ShariqMVP Tuesday, November 8, 2016 1:22 PM Related to Testing
    Monday, November 7, 2016 11:17 PM

All replies

  • Hi gib,

    I am trying to involve someone familiar with this topic to further look at this issue. There might be some time delay. Appreciate your patience.

    Sincerely,

    Oscar


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, November 10, 2016 1:31 AM