开发者

MOQ - Mock a Dictionary<string, double> object

I have the following setup for 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);

When running a test method, I pass in bigMoq as the arguement.

The following works:

bigMoqVar.ComplexityWeights["COMPLEX"] // correctly returns 6

However, this does not:

bigMoqVar.ComplexityWeights.ContainsKey("COMPLEX")  // returns false instead of true

What is the recommended way to support the ContainsKey on the innerMoq?


That's because you didn't setup an expectation for ContainsKey. You will need to setup that manually, Moq has no knowledge of the semantics of the interface.

innerMoq.Setup(d => d.ContainsKey("COMPLEX")).Returns(true);

However, if this is just an IDictionary you need, why go through the mocking framework ? Just create a Dictionary<string,double> with the objects you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜