How to change behaviour of stubs?

后端 未结 1 410
暗喜
暗喜 2020-12-15 19:39

Can I change the behaviour of a stub during runtime? Something like:

    public interface IFoo { string GetBar(); }
    [TestMethod]
    public void TestRhin         


        
相关标签:
1条回答
  • 2020-12-15 20:08

    WARNING

    Changing the behaviour of stubs is a code smell!

    It typically indicates that your unit tests are too complicated, are hard to understand and are brittle, breaking easily on correct changes of the class under test.

    Check out:

    • [xUnit Test Patterns][1]
    • [The Art Of Unit Testing][2]

    So, please: only use this solution if you can't avoid it. In my eyes this article borders on bad advice - however there are rare situations where you really need it.


    Ah, I figured it out myself. Rhino supports record/replay mode. While AAA syntax always keeps the objects in replay mode we can switch to record and back to replay just to clear the stub's behaviour.

    It looks a little hackish, however ...

        public interface IFoo { string GetBar(); }
        [TestMethod]
        public void TestRhino()
        {
            var fi = MockRepository.GenerateStub<IFoo>();
            fi.Stub(x => x.GetBar()).Return("A");
            Assert.AreEqual("A", fi.GetBar());
    
            // Switch to record to clear behaviour and then back to replay
            fi.BackToRecord(BackToRecordOptions.All);
            fi.Replay();
    
            fi.Stub(x => x.GetBar()).Return("B");
            Assert.AreEqual("B", fi.GetBar());
        }
    

    Update:

    I'll be using this in the future, so things look a little nicer:

    internal static class MockExtension {
        public static void ClearBehavior<T>(this T fi)
        {
            // Switch back to record and then to replay - that 
            // clears all behaviour and we can program new behavior.
            // Record/Replay do not occur otherwise in our tests, that another method of
            // using Rhino Mocks.
    
            fi.BackToRecord(BackToRecordOptions.All);
            fi.Replay();
        }
    }
    
    0 讨论(0)
提交回复
热议问题