Digbyswift
Digbyswift

Reputation: 10400

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.

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".

Obviously the code x => x.Calculate = CalculatorHelper.Calculate is incorrect but what would the correct way to code this?

Upvotes: 8

Views: 7305

Answers (2)

k.m
k.m

Reputation: 31454

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):

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));

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

Calculate should return a new Action pointing to CalculatorHelper.Calculate, so it should be:

_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.

Upvotes: 9

Related Questions