views:

312

answers:

2

I have a function I want to Moq. The problem is that it takes 5 parameters. The framework only contains Action<T1,T2,T3,T4> and Moq's generic CallBack() only overloads Action and the four generic versions. Is there an elegant workaround for this?

This is what I want to do:

public class Filter : IFilter  
{  
    public int Filter(int i1, int i2, int i3, int i4, int i5){return 0;}  
}

//Moq code:
var mocker = new Mock<IFilter>();  
mocker.Setup(x => x.Filter(  
    It.IsAny<int>(),  
    It.IsAny<int>(),  
    It.IsAny<int>(),  
    It.IsAny<int>(),  
    It.IsAny<int>(),  
    It.IsAny<int>())  
.Callback
(  
    (int i1, int i2, int i3, int i4, int i5) => i1 * 2  
);  

Moq doesn't allow this because there is no generic Action that takes 5+ parameters. I've resorted to making my own stub. Obviously, it would be better to use Moq with all of its verifications, etc.

+2  A: 

I know this probably breaks your design, but with that many parameters wouldn't it be better to pass a param array?

Robert Harvey
+1, although a Parameter Object might be better if the arguments represent different concepts
Mark Seemann
As you alluded to in your next response, I would need to change Moq itself since it doesn't allow for this overload. Regardless, I need generics so I can access the invocation parameters.
beerncircus
Actually, as Mark points out, a better solution is to pass an object containing all of the parameters you need. Of course, that will change the way you mock it.
Robert Harvey
A: 

This is actually quite simple. Just define your own Action<T1, T2, T3, T4, T5> and you're good to go.

public delegate void Action<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5);

This is all that the Action, Action<T>, ..., Action<T1, T2, T3, T4> are defined as in the framework. Nothing more. Simple!

Enigmativity
You would still have to modify the Moq source code to support more than four parameters in a callback.
Robert Harvey
@"Robert Harvey" - Yes, you're right. I overlooked that. Perhaps Currying could be of use?
Enigmativity
Changing Moq overloads to take an Action of 5+ parameters is the only solution I see. What do you mean by "currying"?
beerncircus