How to set values in GetName in IDataReader?

145 Views Asked by At

I am using Rhino Mocks to test the following method.

    public static List<string> RetrieveColumnNames(IDataReader reader)
    {
        List<string> columns = null;

        for (int i = 0; i < reader.FieldCount; i++)
        {
            columns.Add(reader.GetName(i));
        }

        return columns;
    }

Have something like this but don't know how to continue:

    [TestMethod()]
    public void RetrieveColumnNamesTest()
    {
        //Arrange
        IDataReader reader = MockRepository.GenerateStub<IDataReader>();

        reader.Stub(x => x.FieldCount).Return(2);
        reader.Stub(x => x.name...) // not gonna happen

        //Act
        using (reader)
        {
            List<string> list = RetrieveColumnNames(reader);

            //Assert
            Assert.AreEqual(2, list.Count);
        }

    }

But how can I arrange values in method GetName for test?

2

There are 2 best solutions below

3
Amittai Shapira On

You should use simply use Repeat:
In case you want the same value to be returned:

reader.Stub(x => x.GetName(0)).IgnoreArguments().Repeat.Any().Return("My Name");

In case you want different values to be returned:

reader.Stub(x => x.GetName(0)).IgnoreArguments().Repeat.Once().Return("First Name");
reader.Stub(x => x.GetName(0)).IgnoreArguments().Repeat.Once().Return("Second Name");
0
Old Fox On

The correct way to write your UT is:

[TestMethod]
public void TestMethod1()
{
    const string FIRST = "First Name";
    const string SECOND = "Second Name";

    var reader = MockRepository.GenerateStub<IDataReader>();

    reader.Stub(x => x.FieldCount).Return(2);
    reader.Stub(x => x.GetName(0)).Return(FIRST);
    reader.Stub(x => x.GetName(1)).Return(SECOND);

    var actual = RetrieveColumnNames(reader);

    CollectionAssert.AreEquivalent(new [] {FIRST, SECOND}, actual);

}

It is a bad practice to use IgnoreArguments().Repeat.Once() in this case, basically because can make problems with calls ordering(and it less readable...), another option is to use Do method with List<string>.

CollectionAssert provides the best functionality to verify the return value.

BTW; you didn't initialize the columns to new instance