【问题标题】:Is it possible to stub a property in Moq and have an event raised on the set operation?是否可以在 Moq 中存根属性并在设置操作中引发事件?
【发布时间】:2014-02-19 17:37:27
【问题描述】:

我想在一个模拟对象上存根一个属性,并在我的测试调用该属性的设置器时触发一个事件。类似于以下内容。给定:

public interface ISomething
{
    event Action FooChanged;
    int Foo { get; set; }
}

我想要一个这样的测试(当然这不会编译):

[Test]
public void HandleChangeInDependencyObject()
{
    var mock = new Mock<ISomething>();
    mock.SetupProperty(m => m.Foo).Raises(m => m.FooChanged += null);
    mock.Object.Foo = 5; // raises the FooChanged event on ISomething
    ...
}

起订量可以做到这一点吗?我只能在 Google 网上论坛论坛上找到 a post from 2009 讨论它。

【问题讨论】:

    标签: unit-testing events properties moq


    【解决方案1】:

    这对我有用:

    var mock = new Mock<ISomething>();
    var raised = false;
    // Setup the property to only raise an event it '5' is passed.  Instead of '5' you can
    // specify It.IsAny<int>() to fire on any value, or It.Is<int>(expr) to fire on some
    // range of values.
    mock.SetupSet(m => m.Foo = 5).Raises(s => s.FooChanged += null);
    mock.Object.FooChanged += () =>
        {
            Console.WriteLine("FooChanged fired");
            raised = true;
        };
    
    Console.WriteLine("Setting Foo to 5...");
    mock.Object.Foo = 5; // raises the FooChanged event on ISomething
    Assert.That(raised, Is.True);
    
    // Make sure the event is not raised if the set value is not in range
    Console.WriteLine("Setting Foo to 6...");
    raised = false;
    mock.Object.Foo = 6; // No setup for '6'
    Assert.That(raised, Is.False);
    

    这有点违反直觉,但是因为事件委托不能在定义它们的类之外调用,所以引用它们的唯一方法是提供一个有效但毫无意义的 MoQ 可以从中提取事件引用的方法,例如 @ 987654323@.

    (感谢 this StackOverflow post 提供关键信息。)

    【讨论】:

    • 谢谢杰西。我确实考虑过这样做 - 但我想要在模拟中使用真正的存根属性,因为我需要测试我的被测单元是否正确设置它。
    • @BrianStewart 你不能直接使用VerifySet 吗?
    • 是的,这就是我最终所做的。我猜我在 Google Groups 论坛帖子中看到的功能从未实现过。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 2018-03-10
    • 2012-07-26
    相关资源
    最近更新 更多