如何模拟返回与MOQ一个int的方法 [英] How to mock a method that returns an int with MOQ

查看:102
本文介绍了如何模拟返回与MOQ一个int的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有确实的内容有一些检索的一类,它有需要取回之前一些输入(过滤器)的方法。其中的投入的呼吁另一种方法,它基本上返回一个int,我怎么嘲笑它使用起订量?这里有一个例子:

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, which basically returning an int, how do I mock it using MOQ? Here's an example:

namespace MyNamespace
{
    public class ConfigMetaDataColumns : MyModel
    {
        public int FieldID { get { return ValueInt("FieldID"); } }
        public int OrderId { get { return ValueInt("OrderId"); } }
        public string Label { get { return ValueString("Label"); } }
        public string FieldName { get { return ValueString("FieldName"); } }
        public int IsReadOnly { get { return ValueInt("IsReadOnly"); } }
    }

    public class GetDataClass
    {
        protected OpenSQLAccessLayer m_WITObject;

        // Input Properties
        public string GroupID;
        public string PageName;

        // Output Properties

        /// <summary>
        /// Get Config meta data
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ConfigMetaDataColumns> GetConfigMetaData()
        {
            var requester = new ListRequester<OpenSQL, ConfigMetaDataColumns>(m_WITObject, "Result[0].RowCount", "Result[0].Row[{0}].");

            return requester.Items;
        }

        public void InitRequest()
        {
            User user = (User)HttpContext.Current.User;
            m_WITObject = user.NewService<OpenSQLAccessLayer>();

            m_WITObject.SetInput("MultipleResultSets", 1);
            m_WITObject.SetInput("ClientID", Utils.GetClientID());
            m_WITObject.SetInput("GroupID", GroupID);
            m_WITObject.SetInput("PageName", PageName);
            m_WITObject.Retrieve();
        }
    }
}

这是GetClientID()方法:

This is the "GetClientID()" method:

public static int GetClientID()
        {
            User oUser = (User)HttpContext.Current.User;
            int nClientID;
            string sClientID = string.Empty;

            if (String.IsNullOrEmpty(oUser.Session("clientid")))
            {
                Client oClient = new Client();
            }

            oUser = (User)HttpContext.Current.User;
            sClientID = oUser.Session("clientid");




            //If we couldn't retrieve it, throw exception
            if ( string.IsNullOrEmpty(sClientID) || !int.TryParse(sClientID, out nClientID))
            {
                throw new Exception("No clientid found in user session, client not authenticated, please login from main page");
            }

            return nClientID;
        }

我只是在寻找一种方式对我来说,传递的ClientID的一个硬codeD的价值,并以此做一些单元测试与 GetDataClass 类。

感谢。

推荐答案

您不能模拟的静态方法。您应该使用依赖注入的一些手段。假设你让你的 GetClientId 方法称为接口的一部分 IUtils 像这样:

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();
} 

和你有你的具体类 utils的实施如上,但没有方法是静态的(和实施过程中的接口)。 现在注入的实现你的界面进入 GetDataClass 通过改变它的构造,像这样的类:

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
}

InitRequest 方法,你改变呼叫 Utils.GetClientID()此.utils.GetClientId()

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

您现在已经准备好了模拟,像这样实例化 GetDataClass 类:

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();

这就是它。

这篇关于如何模拟返回与MOQ一个int的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆