How to mock a method that returns an int with MOQ

微笑、不失礼 提交于 2019-12-01 21:03:55

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<IUtils>();
utilsMock.Setup(u => u.GetClientId()).Returns(42);

var getDataClass = new GetDataClass(utilsMock.Object);
getDataClass.InitRequest();

And that's it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!