MOQ - 模拟一个Dictionary <string,double>对象

Sha*_*awn 2 tdd moq asp.net-mvc-3

我为Moq设置了以下设置:

... other code to setup bigMoq object ...
var innerMoq = new Mock<IDictionary<string, double>>();
innerMoq.SetupGet(d => d["COMPLEX"]).Returns(6d);
innerMoq.SetupGet(d => d["MEDIUM"]).Returns(8d);
innerMoq.SetupGet(d => d["SIMPLE"]).Returns(10d);
bigMoq.SetupGet(d => d.ComplexityWeights).Returns(x.Object);
Run Code Online (Sandbox Code Playgroud)

运行测试方法时,我传入bigMoq作为争论.

以下作品:

bigMoqVar.ComplexityWeights["COMPLEX"] // correctly returns 6
Run Code Online (Sandbox Code Playgroud)

但是,这不是:

bigMoqVar.ComplexityWeights.ContainsKey("COMPLEX")  // returns false instead of true
Run Code Online (Sandbox Code Playgroud)

在innerMoq上支持ContainsKey的推荐方法是什么?

dri*_*iis 6

那是因为你没有设定期望ContainsKey.您需要手动设置,Moq不知道接口的语义.

innerMoq.Setup(d => d.ContainsKey("COMPLEX")).Returns(true);
Run Code Online (Sandbox Code Playgroud)

但是,如果这只是IDictionary你需要的,为什么要通过模拟框架呢?只需Dictionary<string,double>使用您需要的对象创建一个.