How do I mock a class without an interface?

前端 未结 8 1278
[愿得一人]
[愿得一人] 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条回答
  •  旧时难觅i
    2020-12-01 00:34

    I think it's better to create an interface for that class. And create a unit test using interface.

    If it you don't have access to that class, you can create an adapter for that class.

    For example:

    public class RealClass
    {
        int DoSomething(string input)
        {
            // real implementation here
        }
    }
    
    public interface IRealClassAdapter
    {
        int DoSomething(string input);
    }
    
    public class RealClassAdapter : IRealClassAdapter
    {
        readonly RealClass _realClass;
    
        public RealClassAdapter() => _realClass = new RealClass();
    
        int DoSomething(string input) => _realClass.DoSomething(input);
    }
    

    This way, you can easily create mock for your class using IRealClassAdapter.

    Hope it works.

提交回复
热议问题