Skip to content

Instantly share code, notes, and snippets.

@cknaap
Created December 13, 2016 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cknaap/5ac0c763f2323a7aaaaea2a9738277e3 to your computer and use it in GitHub Desktop.
Save cknaap/5ac0c763f2323a7aaaaea2a9738277e3 to your computer and use it in GitHub Desktop.
How to express an expected call on a Moq mock in the memberdata for an XUnit Theory.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Moq;
using Xunit;
namespace DynamicVerify
{
public class ExpectedCallFromMemberData
{
[Theory]
[MemberData(nameof(GetMemberData))]
public void Bar_calls_right_method_on_IFoo(int number, Expression<Action<IFoo>> expectedCall, Times times, string message)
{
var fooMock = new Mock<IFoo>();
var sut = new Bar(fooMock.Object);
sut.DoBar(number);
fooMock.Verify(expectedCall, times, message);
}
private static IEnumerable<object[]> GetMemberData()
{
Func<Expression<Action<IFoo>>, Expression<Action<IFoo>>> fooCall = action => action;
return new List<object[]> {
new object[] {1, fooCall(foo => foo.DoFoo1()), Times.Once(), "Expected call on DoFoo1." },
new object[] {2, fooCall(foo => foo.DoFoo2()), Times.Once(), "Expected call on DoFoo2." },
new object[] {3, fooCall(foo => foo.DoFoo1()), Times.Never(), "Argument 3 should not call IFoo at all." },
};
}
}
public interface IFoo
{
void DoFoo1();
void DoFoo2();
}
public class Bar
{
private IFoo _foo;
public Bar(IFoo foo)
{
_foo = foo;
}
public void DoBar(int number)
{
if (number == 1)
_foo.DoFoo1();
else if (number == 2)
_foo.DoFoo2();
}
}
}
@gradyal
Copy link

gradyal commented Sep 13, 2018

I stumbled onto this and I cannot for the life of be get this to work. It grabs the member data, but never hits the test method. Do you have this running with the latest version of xUnit (2.4)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment