如何基于接口创建模拟对象并设置只读属性?

时间:2008-12-12 11:49:38

标签: tdd rhino-mocks

我是TDD的新手。所以任何帮助将不胜感激。我正在使用NUnit和Rhino模拟器。 如何在模拟对象中将ID值设置为1?

我看了一眼:http://www.iamnotmyself.com/2008/06/26/RhinoMocksAndReadOnlyPropertyInjectionPart2.aspx 但反射似乎不适用于界面。

    public interface IBatchInfo
    {
        int ID { get;}
        Branches Branch { get; set; }
        string Description { get; set; }                                
    }

 [SetUp]
       public void PerFixtureSetup()
       {

           _mocks = new MockRepository();
           _testRepository = _mocks.StrictMock<IOLERepository>();

       }

    [Test]
            public void ItemsAreReturned()
            {
                IBatchInfo aBatchItem=  _mocks.Stub<IBatchInfo>();

                aBatchItem.ID = 1; //fails because ID is a readonly property
                aBatchItem.Branch = Branches.Edinburgh;


                List<IBatchInfo> list = new List<IBatchInfo>();

                list.Add( aBatchItem);

                Expect.Call(_testRepository.BatchListActive()).Return(list);
                _mocks.ReplayAll();

                BatchList bf = new BatchList(_testRepository, "usercreated", (IDBUpdateNotifier)DBUpdateNotifier.Instance);
                List<Batch> listofBatch = bf.Items;

                Assert.AreEqual(1, listofBatch.Count);
                Assert.AreEqual(1, listofBatch[0].ID);
                Assert.AreEqual( Branches.Edinburgh,listofBatch[0].Branch);
            }

2 个答案:

答案 0 :(得分:1)

http://haacked.com/archive/2007/05/04/setting-propertybehavior-on-all-properties-with-rhino-mocks.aspx找到答案。

简单,而不是

aBatchItem.ID=1;

使用:

SetupResult.For(aBatchItem.ID).Return(1);

答案 1 :(得分:1)

如果使用犀牛模拟3.5更好:

aBatch.Stub(x => x.ID).Return(0);
豫ICP备18024241号-1