如何模拟使用MOQ返回int的方法

我有一个类来检索内容,它有一个方法,在检索它之前需要一些输入(filter)。 其中一个“输入”调用另一个方法,它基本上返回一个int,如何使用MOQ模拟它? 这是一个例子:

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 ///  /// Get Config meta data ///  ///  public IEnumerable GetConfigMetaData() { var requester = new ListRequester(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(); 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()”方法:

 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的硬编码值,并使用它来使用GetDataClass类进行一些unit testing。

谢谢。

你不能模拟静态方法。 你应该使用一些dependency injection的方法。 假设您将GetClientId方法作为名为IUtils的接口的一部分, IUtils所示:

 public interface IUtils { int GetClientId(); } 

并且您具有如上所述实现的具体类Utils ,但没有该方法是静态的(并且当然实现了接口)。 您现在通过更改其构造函数将接口的实现注入GetDataClass类,如下所示:

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

InitRequest方法中,将调用Utils.GetClientID()更改为this.utils.GetClientId()

您现在可以使用mock来实例化GetDataClass类,如下所示:

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

就是这样。