How to Mock (with Moq) Unity methods

后端 未结 4 1153
别跟我提以往
别跟我提以往 2021-01-04 04:04

Extension methods are not good for testing (that\'s described here: Mocking Extension Methods with Moq, http://www.clariusconsulting.net/blogs/kzu/archive/2009/12/22/Howtomo

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 04:53

    Remove the dependency on IUnityContainer and things become a lot easier and cleaner. Instead let unity inject your dependencies which are abstracted into interfaces. These are easily mocked. Here's an example using a little trick with Unity that injects an auto-factory for IMyLog.

    public class MyManager
    {
       private readonly Func logFactory;
    
       public MyManager(Func logFactory) 
       {
           this.logFactory = logFactory;
       }
    
       public IResult DoJob(IData data)
       {
           IMyLog log = logFactory();
    
           ...
       }
    }
    

    Or if you don't need to create the instance each time:

    public class MyManager
    {
       private readonly IMyLog myLog;
    
       public MyManager(IMyLog myLog) 
       {
           this.myLog = myLog;
       }
    
       public IResult DoJob(IData data)
       {
           ...
       }
    }
    

提交回复
热议问题