Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

c# - Mocking a DataReader and getting a Rhino.Mocks.Exceptions.ExpectationViolationException: IDisposable.Dispose(); Expected #0, Actual #1

I'm trying to mock a SqlDataReader

 SqlDataReader reader = mocks.CreateMock<SqlDataReader>();
 Expect.Call(reader.Read()).Return(true).Repeat.Times(1);
 Expect.Call(reader.Read()).Return(false);
 Expect.Call(reader.HasRows).Return(true);
 Expect.Call(reader.Dispose);
 Expect.Call(reader["City"]).Return("Boise");
 Expect.Call(reader["State"]).Return("State");
 Expect.Call(reader["LAT"]).Return(100);
 Expect.Call(reader["LON"]).Return(-100);
 mocks.ReplayAll();

but I keep getting a Rhino.Mocks.Exceptions.ExpectationViolationException: IDisposable.Dispose(); Expected #0, Actual #1 error in my method

        using (reader)
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    CityState myCity = new CityState
                       {
                           City = reader["City"].ToString(),
                           State = reader["State"].ToString(),
                           Lat = Convert.ToInt32(reader["LAT"]),
                           Lon = Convert.ToInt32(reader["LON"])
                       };
                    myCities.Add(myCity);
                }                    
            }               
        }

am I missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will suggest you a rewrite of the test using AAA syntax and using an interface (IDataReader) instead of concrete type (SqlDataReader):

// Arrange
IDataReader reader = MockRepository.GenerateStub<IDataReader>();
reader.Stub(x => x.Read()).Repeat.Once().Return(true);
reader.Stub(x => x.Read()).Return(false);
reader.Stub(x => x["City"]).Return("Boise");
reader.Stub(x => x["State"]).Return("State");
reader.Stub(x => x["LAT"]).Return(100);
reader.Stub(x => x["LON"]).Return(-100);

// Act
var myCities = new List<CityState>();
using (reader)
{
    while (reader.Read())
    {
        CityState myCity = new CityState
        {
            City = reader["City"].ToString(),
            State = reader["State"].ToString(),
            Lat = Convert.ToInt32(reader["LAT"]),
            Lon = Convert.ToInt32(reader["LON"])
        };
        myCities.Add(myCity);
    }
}

// Assert
Assert.AreEqual(1, myCities.Count);
Assert.AreEqual("Boise", myCities[0].City);
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...