【问题标题】:Moq + Unit Testing -- How can I pass an Action to my class to test if that Action gets invoked?Moq + 单元测试——我如何将一个动作传递给我的班级以测试该动作是否被调用?
【发布时间】:2011-10-11 17:19:51
【问题描述】:

基本上,我的类上有一个方法,如果满足某些条件,它会调用Action<T>。如何进行单元测试以确保调用该操作?

public class MyClass<T>
{
    private IDBService _dbService;

    private Action<T> _action;

    public MyClass(IDBService dbService, Action<T> action)
    {
        if (dbService == null) throw new ArgumentNullException("dbService");
        if (action == null) throw new ArgumentNullException("action");

        _dbService = dbService;
        _action = action;
    }

    public void CallActionIfPossible(T param)
    {
        if (_dbService.IsTopUser)
            action(param);
    }
}

【问题讨论】:

  • 向我们展示您当前的代码,以便我们做出回应?

标签: c# unit-testing action moq invoke


【解决方案1】:

嗯,基本思想是Action&lt;T&gt; 在某处产生了一些状态变化(如果没有,那有什么意义?)。因此,单元测试当条件成立时会发生预期的状态变化,而当条件不成立时不会发生预期的状态变化。

当然,理想情况下,你可以模拟Action&lt;T&gt;,这样状态测试就超级简单了。您不需要 Moq 或任何其他模拟框架:

bool actionWasInvoked = false;
Action<Foo> action = foo => actionWasInvoked = true;
Bar<Foo> bar = new Bar<Foo>();
// set up conditions that should guarantee action is invoked
bar.M(action);
Assert.IsTrue(actionWasInvoked);

bool actionWasInvoked = false;
Action<Foo> action = foo => actionWasInvoked = true;
Bar<Foo> bar = new Bar<Foo>();
// set up conditions that should guarantee action is NOT invoked
bar.M(action);
Assert.IsFalse(actionWasInvoked);

当然,我不知道您的确切设置。也许你在构造Bar 时传入action,或者你有其他设置动作的方法。但是思路应该很清楚。

【讨论】:

    【解决方案2】:

    Jason 的回答很好,但一个经常被忽视的警告是,您经常需要测试一定数量的调用(例如,它不仅被调用,而且只被调用一次)。所以我经常做这样的事情:

    var callCount = 0;
    Action<Foo> action = _ => callCount++;
    Bar<Foo> bar = new Bar<Foo>();
    // set up conditions that should guarantee action is invoked
    bar.M(action);
    Assert.That(callCount, Is.EqualTo(1));
    

    【讨论】:

    • +1 我喜欢这背后的想法(确保它有所需的调用次数)。
    猜你喜欢
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2012-05-22
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多