【发布时间】:2015-09-30 05:35:04
【问题描述】:
我有一个从基类扩展而来的类,基类在另一个 dll 中。
public class MyMicroBlogCache : RelatedBase<THZUserInfo, MicroBlogCacheModel, int>
在构造函数中,注入一个ICache
public MyMicroBlogCache(ICache cache,....
在基类中,我在方法中使用 ICache(例如 void A())
我写了一个单元测试,模拟 ICache
var cache = Substitute.For<ICache>();
cache.PageRelated<THZUserInfo, MicroBlogCacheModel, int>("My", 2217, 0, 3, out all, true)
.Returns(
x =>
{
var list = new List<MicroBlogCacheModel>();
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
return list;
});
用 NSubstitute 模拟
var cache1 = new Mock<ICache>();
cache1.Setup(ca => ca.PageRelated<THZUserInfo, MicroBlogCacheModel, int>("My", 2217, 0, 3, out all, true))
.Returns(
() =>
{
var list = new List<MicroBlogCacheModel>();
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
return list;
});
或模拟起订量
奇怪的是:
当我在基类(RelatedBase)中调用方法写入时,方法(例如 A())调用模拟 ICache,它不返回模拟数据。
如果我覆盖子类(MyMicroBlogCache)中的方法,并使用相同的代码(覆盖并从基类复制代码),它将返回模拟数据。
如果我覆盖并使用 base.A(...) ,它不会返回模拟数据。
所以,基类中的代码是错误的,子类中的代码是正确的。
如果我创建一个类实现 ICache,没关系
NSubstitute 和 Moq 都是一样的。
我用 vs2015、vs2013 试试这个;.net 4.5
为什么会发生,我该如何解决它
更新:
var cache1 = new Mock<ICache>(MockBehavior.Strict);
cache1.Setup(ca => ca.PageRelated<THZUserInfo, MicroBlogCacheModel, int>("My", 2217, 0, 3, out all, true))
.Returns(
() =>
{
var list = new List<MicroBlogCacheModel>();
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
list.Add(new MicroBlogCacheModel { Id = 1, UserId = 2217 });
return list;
});
然后测试方法调用
var r = my.GetRelatedPage(2217, 0, 3, out all, true);
在基类中调用
var list = cache.PageRelated<TMainKey, TChild, TMainKey>("My", key, skip, take, out all, desc);
key=2217,skip=0,take=3,desc=true,
【问题讨论】:
标签: visual-studio moq mstest nsubstitute