How to mock a method that returns an int with MOQ

后端 未结 1 1692
误落风尘
误落风尘 2021-01-19 04:04

I have a class that does some retrieving of contents, and it has a method that requires some inputs (filters) before retrieving it. One of the \"input\" calls another method

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 04:46

    You cannot mock a static method. You should use some means of dependency injection. Say you make your GetClientId method part of an interface called IUtils like so:

    public interface IUtils
    {
        int GetClientId();
    } 
    

    And you have your concrete class Utils implemented as above, but without the method being static (and implementing the interface of course). You now inject an implementation of your interface into the GetDataClass class by changing its constructor, like so:

    public class GetDataClass
    {
         private readonly IUtils utils;
    
         public GetDataClass(IUtils utils)
         {
             this.utils = utils;
         }
    
         //SNIP
    }
    

    In the InitRequest method you change the call Utils.GetClientID() to this.utils.GetClientId().

    You are now ready to instantiate your GetDataClass class with a mock, like so:

    var utilsMock = new Mock();
    utilsMock.Setup(u => u.GetClientId()).Returns(42);
    
    var getDataClass = new GetDataClass(utilsMock.Object);
    getDataClass.InitRequest();
    

    And that's it.

    0 讨论(0)
提交回复
热议问题