tags:

views:

240

answers:

1

Is it possible to get access to the parameter used to make a call to a mocked expectation when assembling the Returns object?

Here is a stub for the objects involved and, given that, I am trying to mock a Collection:

Class CollectionValue {
    public Id { get; set; }
}
Class Collection {
    private List<CollectionValue> AllValues { get; set; }
    public List<CollectionValue> GetById(List<int> ids) {
        return AllValues.Where(v => ids.Contains(v.Id));
    }
}

Given a test list of CollectionValues that will be used for the mocked object, how does one go about setting up an expectation that will handle every possible permutation of the IDs in that list of CollectionValues, including calls that combine existing IDs and non-existing IDs? My problem comes from a desire to set up all possible expectations in a single call; if access to the original parameter isn't possible, I could just as easily set up just the exact expectation I want to test in a given call each time.

Here is what I was hoping to do, where "???" represents where it would be handy to have access to the parameter used to call GetById (the one that qualified the It.IsAny restriction):

CollectionMock.Expect(c => c.GetById(It.IsAny<List<int>>())).Returns(???);
+4  A: 

From the moq quickstart guide:

// access invocation arguments when returning a value
mock.Setup(x => x.Execute(It.IsAny<string>()))
                .Returns((string s) => s.ToLower());

Which suggests therefore that you can fill in your ??? as

CollectionMock.Expect(c => c.GetById(It.IsAny<List<int>>()))
              .Returns((List<int> l) => //Do some stuff with l
                      );
BenA