断言回调动作是用nUnit执行的

时间:2013-06-27 15:29:29

标签: c# unit-testing nunit

我有一个有2个回调操作的类:

public class MyClass
{
    public void DoSomething(Action onSuccess, Action onFailure)
    { }
}

我正在尝试为此编写测试,但不确定如何'断言'我的onSuccess已被执行?

[Test]
public void ChangePassword_returns_false_if_user_does_not_exist()
{
    var myClass = new MyClass(mockedDependency.Object);

    myClass.DoSomething( //what do i need to pass in, in order to Assert that onSuccess Action was executed?)
}

1 个答案:

答案 0 :(得分:5)

您可以创建更改某些标志的操作:

[Test]
public void ChangePassword_returns_false_if_user_does_not_exist()
{
    var myClass = new MyClass(mockedDependency.Object);
    bool isExecuted = false; // flag to check
    Action success = () => isExecuted = true; // set flag to true when executed

    myClass.DoSomething(success, null);
    Assert.IsTrue(isExecuted); // check if flag changed
}

甚至使用就地lambda来改变标志:

[Test]
public void ChangePassword_returns_false_if_user_does_not_exist()
{
    var myClass = new MyClass(mockedDependency.Object);
    bool isExecuted = false; // flag to check
    myClass.DoSomething(() => isExecuted = true, null);
    Assert.IsTrue(isExecuted); // check if flag changed
}

还有一种方法 - 您可以使用Moq来验证是否已调用操作。在这种情况下,您将不需要任何标志。首先,您需要一些与Action委托签名匹配的方法的接口:

public interface IHelper // consider better name
{
    void ShouldRun();
    void ShouldNotRun();
}

然后你可以使用mock来验证调用动作的时间:

[Test]
public void ChangePassword_returns_false_if_user_does_not_exist()
{
    Mock<IHelper> helper = new Mock<IHelper>();            
    var myClass = new MyClass(ockedDependency.Object);
    myClass.DoSomething(helper.Object.ShouldRun, helper.Object.ShouldNotRun);

    helper.Verify(h => h.ShouldRun(), Times.Once());
    helper.Verify(h => h.ShouldNotRun(), Times.Never());
}