gpt4 book ai didi

c# - 断言表达式

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:48 25 4
gpt4 key购买 nike

我有一个“示例”类,我想为它创建单元测试。看看下面我的类(class):

public class Example 
{
private readonly Calculator _calculator;

public Example(ICalculator calculator)
{
_calculator = calculator;
}

public void Calculate()
{
_calculator.Execute(operation => operation.Subtract());
}
}

public interface IOperation {
void Sum();
void Subtract();
}

public inferface ICalculator {
void Execute(Action<IOperation> action);
}

public class Calculator {
public void Execute(Action<IOperation> action){}
}

我想要的是创建一个单元测试类来验证我的示例类 Calculate 中的方法调用 _calculator.Execute 作为参数传递 操作。减去()。可能吗?

我知道如何模拟我的 ICalculator 并验证 Execute 被调用一次,但我不知道如何验证 Execute 方法是否被调用 operation.Subtract() 作为参数而不是 operation.Sum()

我正在使用 NUnit 创建我的单元测试。在这里您可以看到我的单元测试类目前的情况:

[TestFixture]
public class ExampleTests
{
[Test]
public void Test1()
{
var calculator = new Mock<ICalculator>();
var subject = new Example(calculator.Object);

subject.Calculate();

calculator.Verify(x => x.Execute(It.IsAny<Action<IOperation>>()), Times.Once);
}
}

希望有人能听懂我的英文,抱歉。

最佳答案

您无法直接验证传递的是什么 lambda,但您可以通过实际调用 said lambda 和另一个模拟来绕过它:

var calculator = new Mock<ICalculator>();
var operation = new Mock<IOperation>();
// when calculator's Execute is called, invoke it's argument (Action<IOperation>)
// with mocked IOperation which will later be verified
calculator
.Setup(c => c.Execute(It.IsAny<Action<IOperation>>()))
.Callback<Action<IOperation>>(args => args(operation.Object));
var example = new Example(calculator.Object);

example.Calculate();

calculator.Verify(c => c.Execute(It.IsAny<Action<IOperation>>()));
operation.Verify(o => o.Subtract());

关于c# - 断言表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26893659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com