简体   繁体   English

如何使用Moq验证静态方法调用

[英]How to verify static method call using Moq

Using this approach I have made my static method calls an Action in the hope that I can set and verify the call in my Moq unit test. 使用这种方法我已经让我的静态方法调用一个Action ,希望我可以在我的Moq单元测试中设置和验证调用。

The code being tested is: 正在测试的代码是:

public Action<Data> Calculate = x => CalculatorHelper.Calculate(x);

public void CalculateData(Data data)
{
    ...

    Calculate(data);

    ...
}

And the test is: 测试是:

[Test]
public void CalculateIsCalled()
{
    _mockService.Setup(x => x.Calculate = CalculatorHelper.Calculate)
                .Verifiable();
    ...

    _mockService.VerifyAll();
}

However, the parameter in the Setup() is throwing the compile error "an expression tree cannot contain an assignment operator". 但是, Setup()的参数抛出编译错误“表达式树不能包含赋值运算符”。

Obviously the code x => x.Calculate = CalculatorHelper.Calculate is incorrect but what would the correct way to code this? 显然代码x => x.Calculate = CalculatorHelper.Calculate是不正确的但是正确的编码方式是什么?

Calculate should return a new Action pointing to CalculatorHelper.Calculate , so it should be: Calculate应该返回一个指向CalculatorHelper.Calculate的新Action,所以它应该是:

_mockService.Setup(x => x.Calculate).Returns(CalculatorHelper.Calculate)
            .Verifiable();

However, for this to work, Calculate needs to be a virtual property, not just a field. 但是,要使其工作, Calculate需要是一个virtual属性,而不仅仅是一个字段。

Considering the fact that Calculate is public field, you don't even need Moq here (also assuming you are testing that CalculateData calls the delegate): 考虑到Calculate是公共字段这一事实,你甚至不需要Moq(也假设你正在测试CalculateData调用委托):

Data passedAsActionParameter = null;
var testedClass = new Calculator();
testedClass.Calculate = d => { passedAsActionParameter = d; };
var data = new Data();
testedClass.CalculateData(data);

Assert.That(passedAsActionParameter, Is.EqualTo(data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM