Skip to content

Instantly share code, notes, and snippets.

@memark
Forked from jwChung/MockExtensions.cs
Last active August 29, 2015 14:05
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 memark/0a2e3771519e16eeb122 to your computer and use it in GitHub Desktop.
Save memark/0a2e3771519e16eeb122 to your computer and use it in GitHub Desktop.
namespace Jwc.MoqExtensions
{
using Moq;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Xunit;
public interface IFoo
{
string GetName();
}
public class MockExtensionsTest
{
[Fact]
public void OfCorrectlyConfiguresMockedInstance()
{
var mocked = new Mock<IFoo>().Object;
mocked.Of(x => x.GetName() == "name");
Assert.Equal("name", mocked.GetName());
}
}
public static class MockExtensions
{
private readonly static Type TypeOfMockQueryable
= typeof(Mock).Assembly.GetTypes().Single(t => t.Name == "MockQueryable`1");
public static T Of<T>(this T mocked, Expression<Func<T, bool>> predicate) where T : class
{
return CreateMockQuery<T>(mocked).First(predicate);
}
private static IQueryable<T> CreateMockQuery<T>(T mocked) where T : class
{
return (IQueryable<T>)MockExtensions.GetConstructorOfMockQueryable<T>()
.Invoke(new object[] { MockExtensions.GetMethodCallExpression(mocked) });
}
private static ConstructorInfo GetConstructorOfMockQueryable<T>()
{
return MockExtensions.TypeOfMockQueryable
.MakeGenericType(typeof(T))
.GetConstructor(new[] { typeof(MethodCallExpression) });
}
private static MethodCallExpression GetMethodCallExpression<T>(T mocked) where T : class
{
return Expression.Call(
new Func<T, IQueryable<T>>(m => new[] { m }.AsQueryable()).Method,
Expression.Constant(mocked));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment