微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 模拟一个DataReader并获取Rhino.Mocks.Exceptions.ExpectationViolationException:IDisposable.Dispose();预期#0,实际#1

我试图模拟一个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();

但我不断得到一个Rhino.Mocks.Exceptions.ExpectationViolationException:Idisposable.dispose();预期#0,我的方法中的实际#1错误

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);
                }                    
            }               
        }

我错过了什么吗?

解决方法

我将建议您使用AAA语法和使用接口(IDataReader)而不是具体类型(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(),Lon = Convert.ToInt32(reader["LON"])
        };
        myCities.Add(myCity);
    }
}

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

原文地址:https://www.jb51.cc/csharp/95027.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐