Exemple #1
0
 internal static object IsAny(Type type, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockingContext.CurrentRepository.AddMatcherInContext(new TypeMatcher(type));
         return MockingUtil.CreateInstance(type, args);
     }));
 }
Exemple #2
0
 /// <summary>
 /// Throws a the specified exception for the target async call causing returned task to fail.
 /// </summary>
 /// <returns></returns>
 public IAssertable ThrowsAsync <T>(params object[] args) where T : Exception
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         this.behaviors.Add(new ThrowAsyncExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T), args)));
         return this;
     }));
 }
Exemple #3
0
 /// <summary>
 /// Throws a the specified expection for target call.
 /// </summary>
 /// <returns></returns>
 public IAssertable Throws <T>() where T : Exception
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         this.behaviors.Add(new ThrowExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T))));
         return this;
     }));
 }
Exemple #4
0
        private object CreateMock(Type returnType, MocksRepository repository, Invocation invocation)
        {
            var parentMock = invocation.MockMixin;
            var replicator = parentMock as IMockReplicator;

            object mock = null;

            if (returnType.IsArray)
            {
                mock = Array.CreateInstance(returnType.GetElementType(), Enumerable.Repeat(0, returnType.GetArrayRank()).ToArray());
            }

            var idictionaryType = returnType.GetImplementationOfGenericInterface(typeof(IDictionary <,>));

            if (mock == null && idictionaryType != null)
            {
                var dictType = typeof(Dictionary <,>).MakeGenericType(idictionaryType.GetGenericArguments());
                mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(dictType));
            }

            var ienumerableType = returnType.GetImplementationOfGenericInterface(typeof(IEnumerable <>));

            if (mock == null && ienumerableType != null)
            {
                var listType = typeof(List <>).MakeGenericType(ienumerableType.GetGenericArguments());
                mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(listType));
            }

            if (mock == null && typeof(Task).IsAssignableFrom(returnType))
            {
                var elementType = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>)
                                        ? returnType.GetGenericArguments()[0] : typeof(object);
                var taskResultValue = MustReturnMock(invocation)
                                        ? CreateMock(elementType, repository, invocation)
                                        : elementType.GetDefaultValue();

                Expression <Func <Task <object> > > taskFromResult = () => MockingUtil.TaskFromResult((object)null);
                mock = ((MethodCallExpression)taskFromResult.Body).Method
                       .GetGenericMethodDefinition()
                       .MakeGenericMethod(elementType)
                       .Invoke(null, new object[] { taskResultValue });
            }

#if !PORTABLE
            if (mock == null && returnType.IsByRef)
            {
                var             delegateType = typeof(object).Assembly.GetType("Telerik.JustMock.RefDelegate`1").MakeGenericType(new [] { returnType.GetElementType() });
                ConstructorInfo constructor  = delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) });

                MethodInfo genericMethodInfo = this.GetType().GetMethod("GetDefaultRef", BindingFlags.NonPublic | BindingFlags.Instance);
                MethodInfo methodInfo        = genericMethodInfo.MakeGenericMethod(returnType.GetElementType());

                mock = constructor.Invoke(new object[] { this, methodInfo.MethodHandle.GetFunctionPointer() });
            }
#endif

            if (mock == null && MustReturnMock(invocation, checkPropertyOnTestFixture: true))
            {
                if (typeof(String) == returnType)
                {
                    mock = String.Empty;
                }
                else
                {
                    try
                    {
                        mock = replicator.CreateSimilarMock(repository, returnType, null, true, null);
                    }
                    catch (MockException)
                    { }
                }
            }

            return(mock);
        }
Exemple #5
0
        private object CreateMock(Type returnType, MocksRepository repository, Invocation invocation)
        {
            var parentMock = invocation.MockMixin;
            var replicator = parentMock as IMockReplicator;

            object mock = null;

            if (returnType.IsArray)
            {
                mock = Array.CreateInstance(returnType.GetElementType(), Enumerable.Repeat(0, returnType.GetArrayRank()).ToArray());
            }

            var idictionaryType = returnType.GetImplementationOfGenericInterface(typeof(IDictionary <,>));

            if (mock == null && idictionaryType != null)
            {
                var dictType = typeof(Dictionary <,>).MakeGenericType(idictionaryType.GetGenericArguments());
                mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(dictType));
            }

            var ienumerableType = returnType.GetImplementationOfGenericInterface(typeof(IEnumerable <>));

            if (mock == null && ienumerableType != null)
            {
                var listType = typeof(List <>).MakeGenericType(ienumerableType.GetGenericArguments());
                mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(listType));
            }

            if (mock == null && typeof(Task).IsAssignableFrom(returnType))
            {
                var elementType = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>)
                                        ? returnType.GetGenericArguments()[0] : typeof(object);
                var taskResultValue = MustReturnMock(invocation)
                                        ? CreateMock(elementType, repository, invocation)
                                        : elementType.GetDefaultValue();

                Expression <Func <Task <object> > > taskFromResult = () => MockingUtil.TaskFromResult((object)null);
                mock = ((MethodCallExpression)taskFromResult.Body).Method
                       .GetGenericMethodDefinition()
                       .MakeGenericMethod(elementType)
                       .Invoke(null, new object[] { taskResultValue });
            }

            if (mock == null && MustReturnMock(invocation, checkPropertyOnTestFixture: true))
            {
                if (typeof(String) == returnType)
                {
                    mock = String.Empty;
                }
                else
                {
                    try
                    {
                        mock = replicator.CreateSimilarMock(repository, returnType, null, true, null);
                    }
                    catch (MockException)
                    { }
                }
            }

            return(mock);
        }
        public void Process(Invocation invocation)
        {
            if (invocation.IsReturnValueSet)
            {
                return;
            }

            var returnType = invocation.Method.GetReturnType();

            if (returnType == typeof(void) || returnType.IsValueType)
            {
                return;
            }

            if (invocation.Method.Name == "ToString" && invocation.Method.GetParameters().Length == 0 && invocation.UserProvidedImplementation)
            {
                return;
            }

            object mock = null;
            List <KeyValuePair <object, object> > mocksList;

            if (mocks.TryGetValue(invocation.Method, out mocksList))
            {
                // can't put the key part in a Dictionary,
                // because we can't be sure that GetHashCode() works
                mock = mocksList.FirstOrDefault(kvp => Equals(kvp.Key, invocation.Instance)).Value;
            }

            if (mock == null)
            {
                var parentMock = MocksRepository.GetMockMixinFromInvocation(invocation);
                var repository = parentMock.Repository;
                var replicator = parentMock as IMockReplicator;

                bool mustReturnAMock = invocation.InArrange || this.type == RecursiveMockingBehaviorType.ReturnMock;
                if (mustReturnAMock || this.type == RecursiveMockingBehaviorType.ReturnDefault)
                {
                    if (returnType.IsArray)
                    {
                        mock = Array.CreateInstance(returnType.GetElementType(), Enumerable.Repeat(0, returnType.GetArrayRank()).ToArray());
                    }

                    var idictionaryType = returnType.GetImplementationOfGenericInterface(typeof(IDictionary <,>));
                    if (mock == null && idictionaryType != null)
                    {
                        var dictType = typeof(Dictionary <,>).MakeGenericType(idictionaryType.GetGenericArguments());
                        mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(dictType));
                    }

                    var ienumerableType = returnType.GetImplementationOfGenericInterface(typeof(IEnumerable <>));
                    if (mock == null && ienumerableType != null)
                    {
                        var listType = typeof(List <>).MakeGenericType(ienumerableType.GetGenericArguments());
                        mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(listType));
                    }

                    if (mock == null && mustReturnAMock)
                    {
#if !LITE_EDITION
                        var stackTrace           = new StackTrace();
                        var methodCallingArrange = stackTrace.EnumerateFrames()
                                                   .SkipWhile(m => !Attribute.IsDefined(m, typeof(ArrangeMethodAttribute)))
                                                   .SkipWhile(m => m.Module.Assembly == typeof(MocksRepository).Assembly)
                                                   .FirstOrDefault();

                        if (methodCallingArrange != null && invocation.Method.DeclaringType.IsAssignableFrom(methodCallingArrange.DeclaringType))
                        {
                            return;
                        }
#endif

                        if (typeof(String) == returnType)
                        {
                            mock = String.Empty;
                        }
                        else
                        {
                            try
                            {
                                mock = replicator.CreateSimilarMock(repository, returnType, null, true, null);
                            }
                            catch (MockException)
                            { }
                        }
                    }
                }

                if (mock == null)
                {
                    return;
                }

                if (mocksList == null)
                {
                    mocksList = new List <KeyValuePair <object, object> >();
                    mocks.Add(invocation.Method, mocksList);
                }
                mocksList.Add(new KeyValuePair <object, object>(invocation.Instance, mock));

                var mockMixin = MocksRepository.GetMockMixin(mock, null);
                if (parentMock != null && mockMixin != null)
                {
                    parentMock.DependentMocks.Add(mock);
                }
            }

            invocation.ReturnValue  = mock;
            invocation.CallOriginal = false;
            invocation.UserProvidedImplementation = true;
        }
        public static object Create(Type resultCollectionType, MocksRepository repo, IMockReplicator replicator, IEnumerable collection)
        {
            if (resultCollectionType == typeof(string))
            {
                return(null);
            }

            Type sourceType = collection.GetType();

            if (resultCollectionType.IsAssignableFrom(sourceType))
            {
                return(collection);
            }

            var enumerableType = resultCollectionType.GetImplementationOfGenericInterface(typeof(IEnumerable <>)) ?? typeof(IEnumerable);

            if (!enumerableType.IsAssignableFrom(resultCollectionType))
            {
                throw new MockException("Return value is not an enumerable type.");
            }

            var elementType = enumerableType.IsGenericType ? enumerableType.GetGenericArguments()[0] : typeof(object);

            var ilistType      = typeof(IList <>).MakeGenericType(elementType);
            var iqueryableType = typeof(IQueryable <>).MakeGenericType(elementType);

            IEnumerable list;

            if (typeof(ICollection).IsAssignableFrom(sourceType))
            {
                list = collection;
            }
            else
            {
                var listType   = typeof(List <>).MakeGenericType(elementType);
                var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType);

                var castCollection = castMethod.Invoke(null, new[] { collection });
                list = (IEnumerable)MockingUtil.CreateInstance(listType, castCollection);
            }

            var listBehavior = new DelegatedImplementationBehavior(list,
                                                                   new[]
            {
                ilistType,
                typeof(IList),
            });

            var queryable         = list.AsQueryable();
            var queryableType     = queryable.GetType();
            var queryableBehavior = new DelegatedImplementationBehavior(queryable,
                                                                        new[] { queryableType.GetImplementationOfGenericInterface(typeof(IQueryable <>)) });

            if (replicator != null)
            {
                var mock      = replicator.CreateSimilarMock(repo, resultCollectionType, null, true, null);
                var mockMixin = MocksRepository.GetMockMixin(mock, null);
                mockMixin.FallbackBehaviors.Insert(0, queryableBehavior);
                mockMixin.FallbackBehaviors.Insert(0, listBehavior);
                return(mock);
            }
            else
            {
                return(repo.Create(resultCollectionType, null, Behavior.Loose, MockingUtil.EmptyTypes, null,
                                   null, null, new List <IBehavior> {
                    listBehavior, queryableBehavior
                }));
            }
        }