开发者

How do I use Rhino-mocks when unit testing getters/setters?

开发者 https://www.devze.com 2023-02-06 05:01 出处:网络
I\'m currently learning Rhino-mocks and think I\'m confusing the line between unit t开发者_StackOverflow中文版esting and mocking.In my example below, I have a readonly Count() property for which I am

I'm currently learning Rhino-mocks and think I'm confusing the line between unit t开发者_StackOverflow中文版esting and mocking. In my example below, I have a readonly Count() property for which I am trying to test the Get() on (a very contrived example for discussion purpose only). As the comment on the Assert.AreEqual indicates, the result from the Count() property is 2 when it should be 3.

My question is can I use Rhino-mocks to actually stub an object (in this case a readonly property) and test the logic of the get_Count() property of the mock IProduct object?

    public interface IProduct
    {
        int Count { get; }
    }

    public class Product : IProduct
    {
        private int count;
        public int Count
        {
            get { return count + 1; }
        }
    }

    public class TestFixture
    {
        [NUnit.Framework.Test]
        public void TestProduct()
        {
            MockRepository mock = new MockRepository();
            IProduct product = mock.Stub<IProduct>();

            product.Stub(p => p.Count).Return(2);
            mock.ReplayAll();

            Assert.AreEqual(3, product.Count); //Fails - result from product.Count is 2
            mock.VerifyAll();
        }
    }


You are mocking out the object you are trying to test. This is fundamentally incorrect--you want to mock (or stub) DEPENDENCIES on the objects you are trying to test.

In the case shown above, you would not use mocking at all.

Also see my comment on AAA syntax.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号