-
-
Save memark/0a2e3771519e16eeb122 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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