断言回调操作是用nUnit执行的
本文关键字:nUnit 执行 回调 操作 断言 | 更新日期: 2023-09-27 18:20:05
我有一个类,它有两个回调操作:
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?)
}
您可以创建更改某些标志的操作:
[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());
}