Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

c# - How to Moq Setting an Indexed property

I'm trying to use mock to verify that an index property has been set. Here's a moq-able object with an index:

public class Index
{
    IDictionary<object ,object> _backingField 
        = new Dictionary<object, object>();

    public virtual object this[object key]
    {
        get { return _backingField[key]; }
        set { _backingField[key] = value; }
    }
}

First, tried using Setup():

[Test]
public void MoqUsingSetup()
{
    //arrange
    var index = new Mock<Index>();
    index.Setup(o => o["Key"]).Verifiable();
    // act
    index.Object["Key"] = "Value";
    //assert
    index.Verify();
}

...which fails - it must be verifying against get{}

So, I tried using SetupSet():

[Test]
public void MoqUsingSetupSet()
{
    //arrange
    var index = new Mock<Index>();
    index.SetupSet(o => o["Key"]).Verifiable();
}

... which gives a runtime exception:

System.ArgumentException : Expression is not a property access: o => o["Key"]
at Moq.ExpressionExtensions.ToPropertyInfo(LambdaExpression expression)
at Moq.Mock.SetupSet(Mock mock, Expression`1 expression)
at Moq.MockExtensions.SetupSet(Mock`1 mock, Expression`1 expression)

What's the correct way to accomplish this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work

[Test]
public void MoqUsingSetup()
{
    //arrange
    var index = new Mock();
    index.SetupSet(o => o["Key"] = "Value").Verifiable();
    // act
    index.Object["Key"] = "Value";
    //assert
    index.Verify();
}

You can just treat it like a normal property setter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...