【问题标题】:Mock a class method模拟一个类方法
【发布时间】:2014-06-20 09:46:10
【问题描述】:

我有一个接口IKeyValueStore,我想模拟这个类并设置它的一个方法来返回一些虚拟数据。这种方式我试过了

  var storemock = new Mock<IKeyValueStore>();
  storemock.Setup(m => m.Restore<List<IProductDescription>>(It.IsAny<string>(),null,new StringDataContractSerializer())).Returns(ListOfProductDescriptions);

  private List<IProductDescription> ListOfProductDescriptions()
  {
     var obj1 = new ProductDescription("id1");
     var lst = new List<IProductDescription>();
     lst.Add(obj1);

     return lst;
  }

我正在将此 storemock 对象传递给我的测试类构造函数之一。说 TestClass

var objtestclass = new TestClass(storemock.Object);

和我调用一个方法调用restore方法。

objtestclass.checkstore();

在构造函数期间,我正在设置 IkeyValueStore 类型 _store 私有字段。所以我的 testclass 构造函数是:-

public TestClass(IkeyValueStore store)
{
   _store = store;
} 

我的测试方法(恢复)是:-

Public async Task<IEnumerable<IProductDescription>> checkscore()
{
   // here products is coming null.
   Products = _store.Restore<List<IProductDescription>>(CachedProductsKey, null, new StringDataContractSerializer());
}

问题 :- 在 checkstore 方法中,产品应该有一个产品描述列表,但现在为空。我对 IkeyValueStore 做了一个错误的模拟吗?任何帮助表示赞赏。

【问题讨论】:

    标签: c# unit-testing mocking moq


    【解决方案1】:

    看起来你的问题是第三个参数没有正确匹配,所以你设置的模拟没有被使用。

    在您的设置中而不是使用new StringDataContractSerializer() 尝试It.IsAny&lt;StringDataContractSerializer&gt;()

    【讨论】:

    • 没错。它比较实例。
    • @Matthew 这就是问题所在。谢谢:)
    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 2012-08-04
    • 2019-07-29
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多