using System.Linq.Expressions;
using FakeItEasy.Configuration;
var fake = new Fake<IDummyFactory>();
fake.ReturnForMethod<IDummyFactory, Func<string>, string>(s => s.Create, "testStr");
var result = fake.FakedObject.Create();
Console.WriteLine(result);
public static class FakeExtensions
public static IAnyCallConfigurationWithReturnTypeSpecified<TReturnType> ReturnForMethod<TSUT, TDelegate, TReturnType>(
Expression<Func<TSUT, TDelegate>> methodGroupExpression,
TReturnType returnObject) where TSUT : class
where TDelegate : Delegate
var visitor = new ExtractMethodNameExpressionVisitor<TSUT>();
var methodName = visitor.ExtractMethodName(methodGroupExpression);
throw new InvalidOperationException();
var call = fake.AnyCall().WithReturnType<TReturnType>().Where(s => s.Method.Name == methodName);
call.Returns(returnObject);
class ExtractMethodNameExpressionVisitor<T> : ExpressionVisitor
private string? _methodName;
public string? ExtractMethodName(Expression expression)
protected override Expression VisitConstant(ConstantExpression node)
if (node.Type == typeof(MethodInfo) &&
node.Value is MethodInfo methodInfo &&
methodInfo.DeclaringType == typeof(T))
_methodName = methodInfo.Name;
return base.VisitConstant(node);
public interface IDummyFactory