Reputation: 7692
All to often I write the same argument expression in Setup
and Verify
. Is there a way to make a reference of them?
What I write:
var mock = new Moq<IFoo>();
mock.Setup(m => m.MyMethod(It.Is.Any<string>());
...
mock.Verify(m => m.MyMethod(It.Is.Any<string>()), Times.Once);
Then I have the idea that as Setup
and Verify
share the same parameter it should/could be moved into a common reference like so:
var MyMethodCall = {WHAT SHOUD BE HERE?};
var mock = new Moq<IFoo>();
mock.Setup(m => MyMethodCall);
...
mock.Verify(m => MyMethodCall, Times.Once);
Upvotes: 3
Views: 980
Reputation: 9519
In this case, you could use Verifiable
, then you don't need to specify parameters in Verify
at all. It will verify that specific verifiable Setup
has been invoked.
var mock = new Moq<IFoo>();
mock.Setup(m => m.MyMethod(It.Is.Any<string>()).Verifiable();
...
mock.Verify();
IMO Verifiable
is better choice as Verify(Expression<>)
doesn't work with setups but invocations internally. The explanation bellow:
public class Example
{
public bool IsValid { get; set; }
}
public interface IExample
{
bool Do(Example e);
}
// arrange
Expression<Func<IExample, bool>> expr = m => m.Do(It.Is<Example>(x => x.IsValid));
var mock = new Mock<IExample>();
mock.Setup(expr).Verifiable();
// act
var example = new Example {IsValid = true};
mock.Object.Do(example);
example.IsValid = false;
// assert
mock.Verify(expr, Times.Once);
What the outcome will be? The test will fail, since Verify
will evaluate the expression after object has been changed. If you are using Verify
then the invocation will be captured at the moment of invocation. However this is just a showcase should not happened that often :)
Upvotes: 3
Reputation: 3959
You can create a variable that holds the expression, so you can reuse it:
Expression<Action<IFoo>> expression = x => x.MyMethod(It.Is.Any<string>());
var mock = new Moq<IFoo>();
mock.Setup(expression);
...
mock.Verify(expression, Times.Once);
Upvotes: 4