Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
Shawn Avatar asked Feb 23 '23 01:02

Shawn


1 Answers

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.

like image 170
driis Avatar answered Mar 07 '23 06:03

driis