How do I mock a class without an interface?

前端 未结 8 1269
[愿得一人]
[愿得一人] 2020-11-30 23:50

I am working on .NET 4.0 using C# in Windows 7.

I want to test the communication between some methods using mock. The only problem is that I want to do it without i

8条回答
  •  一生所求
    2020-12-01 00:27

    I faced something like that in one of the old and legacy projects that i worked in that not contains any interfaces or best practice and also it's too hard to enforce them build things again or refactoring the code due to the maturity of the project business, So in my UnitTest project i used to create a Wrapper over the classes that I want to mock and that wrapper implement interface which contains all my needed methods that I want to setup and work with, Now I can mock the wrapper instead of the real class.

    For Example:

    Service you want to test which not contains virtual methods or implement interface

    public class ServiceA{
    
    public void A(){}
    
    public String B(){}
    
    }
    

    Wrapper to moq

    public class ServiceAWrapper : IServiceAWrapper{
    
    public void A(){}
    
    public String B(){}
    
    }
    

    The Wrapper Interface

    public interface IServiceAWrapper{
    
    void A();
    
    String B();
    
    }
    

    In the unit test you can now mock the wrapper:

        public void A_Run_ChangeStateOfX()
        {
        var moq = new Mock();
        moq.Setup(...);
        }
    

    This might be not the best practice, but if your project rules force you in this way, do it. Also Put all your Wrappers inside your Unit Test project or Helper project specified only for the unit tests in order to not overload the project with unneeded wrappers or adaptors.

    Update: This answer from more than a year but in this year i faced a lot of similar scenarios with different solutions. For example it's so easy to use Microsoft Fake Framework to create mocks, fakes and stubs and even test private and protected methods without any interfaces. You can read: https://docs.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017

提交回复
热议问题