15

I'm using MOQ to mock a method call with an expected return list. My method returns a list but i want the mock to make a new list every time the method gets called. What I've done so far:

List<Correlation> expected = new List<Correlation> { new Correlation() { Code = "SelfError1" }, new Correlation() { Code = "SelfError2" } };
Mock<IRPLValidator> selfMock = new Mock<IRPLValidator>();
selfMock.Setup(f => f.Validate()).Returns(expected);

What I'm trying to achieve is to make the mock return a new list every time the method get's called. I've tried this but didn't work:

selfMock.Setup(f => f.Validate()).Returns(new List<Correlation>{ new Correlation() { Code = "SelfError1" }, new Correlation() { Code = "SelfError2" } });

As this didn't worked, I'm thinking maybe Callback is the answer to my question but I didn't find any proper example for reinitializing my list. Any suggestions?

As you may wonder why do I need a new list every time, the problem is that I'm calling the method on different object types making some changes in the list, depending on the object type. Because the mock gives me the same list every time the method is called, I'm always modifying the same object in the memory thus I can't keep track of the changes I'm making on it.

Thanks in advance!

2 Answers 2

24
selfMock.Setup(f => f.Validate()).Returns(() => new List<Correlation>{ new Correlation() { Code = "SelfError1" }, new Correlation() { Code = "SelfError2" } });

You need to turn the value inside the Returns into a function. The version you tried created a single list, then returns just used that. This way, the list is created each time as the returns will call the function each time it is needed.

2
  • Thank you - one day I'll get this whole closure thing.
    – David
    Commented Nov 21, 2012 at 14:59
  • 1
    Wish I would have found this earlier, wasted a day yesterday wondering why my list was not returning updated! Thanks!!!
    – PmanAce
    Commented Jun 3, 2016 at 14:08
2

Return takes a Func<>(and various overloads) delegate as input parameter, thus you can specify not just some data inside Returns method that will be returned as parameter but also functions, that will be executed and the result of the function will be returned back. The solution provided by Rangoric, will work fine in your case.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.