views:

43

answers:

1

Hi all,

I have a method that i want to mock that takes an array as a argument. In a real call, the method would modify this array and the resultant array would be use further along in code. What i tried to do was pass in array to the mocked method call, that had values that would be valid when the array is used again. However what i find is when the call is being made to the mocked method it doesn't use the array i have specfied when setting up the mock, instead using the original array, Is there a way around this problem.

e.g

public interface ITest
{
    int Do(int[] values);
}

public void MyTest
{
    var testMock = new Mock<ITest>();
    int[] returnArray = new int[] {1,2,3};
    testMock.Setup(x => x.Do(returnArray)).Returns(0);
    MyTestObject obj = new MyTestObject();
    obj.TestFunction(testMock.Object);
}

public class MyTestObject
{
  .....
    public void TestFunction(ITest value)
    {
         int [] array = new int[3];
         value.Do(array);
         if (array[0] == 1) 

This is where my test falls down as array is still the null array declared two lines above and not the array i specified in the mocked method call. Hope this explains what i am trying to achieve and if so is there anyway of doing it. Would also be open to using RhinoMocks as well if it could be done that way.

Thank in advance,

Kev

A: 

Hi,

The only thing you have done here is to set up an expectation that your Do method will be called with returnArray as parameter, and that it will return 0 as the result. What you want to do is to

(1) create a strict mock to better see what is being executed (2) setup a call that expects your initial array, and then runs a delegate to set the values to 1, 2, 3

using Rhino Mock this would look like this (using moq it will be equivalent):

private delegate int DoDelegate(int[] values);

    [Test]
    public void MyTest()
    {
        var testMock = MockRepository.GenerateStrictMock<ITest>();
        testMock.Expect(x => x.Do(null))
            .IgnoreArguments()
            .Do(new DoDelegate(delegate(int[] values)
                                 {
                                     values[0] = 1;
                                     values[1] = 2;
                                     values[2] = 3;
                                     return 0;
                                 }));

        //Execution (use your real object here obviously
        int[] array = new int[3];
        testMock.Do(array);
        Assert.AreEqual(1, array[0]);
    }
Grzenio
Cheers MateThat did the job for me.Thanks again,Kev
KevGwy