Mocking Static methods using Rhino.Mocks

前端 未结 6 1083
夕颜
夕颜 2020-11-29 07:14

Is it possible to mock a static method using Rhino.Mocks? If Rhino does not support this, is there a pattern or something which would let me accomplish the same?

6条回答
  •  情书的邮戳
    2020-11-29 07:37

    If you can't use TypeMock to intercept the method call, the recommended pattern to use is to create a proxy that forwards to the non-virtual or static methods you are interested in testing, then set the expectation on the proxy. To illustrate, consider the following classes.

    class TypeToTest
    {
        public void Method() { }
    }
    
    interface ITypeToTest
    {
        void Method();
    }
    
    class TypeToTestProxy : ITypeToTest
    {
        TypeToTest m_type = new TypeToTest();
    
        public void Method() { m_type.Method(); }
    }
    

    By creating this proxy, you can now use an ITypeToTest in place of where you were passing or setting a TypeToTest instance, making sure that the default implementation uses the TypeToTestProxy as it forwards to the real implementation. Then, you can create a mock ITypeToTest in your test code and set expectations accordingly.

    Note that creating these proxies can be very tedious, error-prone, and time consuming. To address this I maintain a library and set of tools that generate assemblies containing these types for you. Please refer to this page for more information.

提交回复
热议问题