9

I am attempting to setup an expectation on a repository. The method makes use of the params keyword:

string GetById(int key, params string[] args);

The expectation I have setup:

var resourceRepo = MockRepository.GenerateMock<IResourceRepository>();
resourceRepo.Expect(r => r.GetById(
    Arg<int>.Is.Equal(123),
    Arg<string>.Is.Equal("Name"),
    Arg<string>.Is.Equal("Super"),
    Arg<string>.Is.Equal("Mario"),
    Arg<string>.Is.Equal("No"),
    Arg<string>.Is.Equal("Yes"),
    Arg<string>.Is.Equal("Maybe")))
    .Return(String.Empty);

throws this exception:

Test method XYZ threw exception: System.InvalidOperationException: Use Arg ONLY within a mock method call while recording. 2 arguments expected, 7 have been defined.

What is wrong with the setup of my expectation?

davmos
  • 9,324
  • 4
  • 40
  • 43
ahsteele
  • 26,243
  • 28
  • 134
  • 248

1 Answers1

10

params is just an array:

var resourceRepo = MockRepository.GenerateMock<IResourceRepository>();
resourceRepo
  .Expect(r => r.GetById(
    Arg<int>.Is.Equal(123),
    Arg<string[]>.List.ContainsAll(new[]
                                   {
                                       "Name",
                                       "Super",
                                       "Mario",
                                       "No",
                                       "Yes",
                                       "Maybe"
                                   })))
  .Return(String.Empty);
ahsteele
  • 26,243
  • 28
  • 134
  • 248
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
  • Agreed, frustratingly Visual Studio was given me an error when I tried this yesterday. I didn't however actually build the app so the "error" was the IDE "losing its mind." #sigh I made a minor modification to your answer as `ContainsAll` requires an IEnumerable. – ahsteele Jul 10 '12 at 17:16
  • @ahsteele. Right, it requires an array. Would have been nice to have params there ... – Stefan Steinegger Jul 11 '12 at 05:43
  • I think the correct answer would be to use `.Equal` instead of `.ContainsAll` there. Contains is not restrictive enough, since it would pass if more things were provided in the original call. – julealgon Feb 13 '14 at 19:10
  • @julealgon: the question is about the syntax, not about details of the test. Take my code with ContainsAll as an example to write your own test according to your needs. – Stefan Steinegger Feb 14 '14 at 06:30
  • Ok, fair enough. I thought you were writing his test in the correct form (still seems like it), in which case `Equal` would have to be used. – julealgon Feb 14 '14 at 12:24
  • I've just come to find this post after having this issue. I came up with a similar solution - except I used a home grown 'SequenceEqual'. HOWEVER I now want to be able to say that say the 1st and 3rd arguments equal x and y, but I don't care what the second argument equals. Any pointers? – Jon H Sep 16 '16 at 15:39