Ejemplo n.º 1
0
        public void Updated_ref_parameter_doesnt_affect_call_specification()
        {
            //arrange
            var source = Substitute.For <IValueSource>();
            var router = SubstitutionContext.Current.GetCallRouterFor(source);

            //Configure our handler to update "ref" argument value
            router.RegisterCustomCallHandlerFactory(state =>
                                                    new ActionHandler(
                                                        call =>
            {
                if (call.GetMethodInfo().Name != nameof(IValueSource.GetValueWithRef))
                {
                    return(RouteAction.Continue());
                }

                var args = call.GetArguments();
                args[0]  = "refArg";

                return(RouteAction.Return("xxx"));
            }));

            string refValue = "ref";

            source.GetValueWithRef(ref refValue).Returns("42");

            //act
            refValue = "ref";
            var result = source.GetValueWithRef(ref refValue);

            //assert
            Assert.That(result, Is.EqualTo("42"));
        }
        public RouteAction Handle(ICall call)
        {
            var mockedDbContext = call.Target();
            var invokedMethod   = call.GetMethodInfo();
            var arguments       = call.GetArguments();

            var modelType = GetModelType(invokedMethod);

            if (modelType == null)
            {
                return(RouteAction.Return(invokedMethod.ReturnType.GetDefaultValue()));
            }

            Logger.LogDebug("Setting up model '{type}'", modelType);

            var modelEntityType = _allModelEntityTypes.SingleOrDefault(x => x.ClrType.Equals(modelType));

            if (modelEntityType == null)
            {
                throw new InvalidOperationException(string.Format(ExceptionMessages.CannotCreateDbSetTypeNotIncludedInModel,
                                                                  invokedMethod.GetGenericArguments().Single().Name));
            }

            var setUpModelMethod = typeof(NoSetUpHandler <TDbContext>).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
                                   .Single(x => x.Name.Equals(modelEntityType.FindPrimaryKey() != null ? "SetUpModel" : "SetUpReadOnlyModel"));

            setUpModelMethod.MakeGenericMethod(modelType).Invoke(this, new[] { mockedDbContext });

            return(RouteAction.Return(invokedMethod.Invoke(mockedDbContext, arguments?.ToArray())));
        }
Ejemplo n.º 3
0
 public RouteAction Handle(ICall call)
 {
     if (_callResults.HasResultFor(call))
     {
         return(RouteAction.Return(_callResults.GetResult(call)));
     }
     return(RouteAction.Continue());
 }
Ejemplo n.º 4
0
        /// <summary>
        ///     Checks the last method invocation on the mock;
        ///     if Add was invoked the unexpected match is set up;
        ///     if GetOrAdd or GetOrAddAsync was invoked the unexpected match is set up and the addItemFactory result will be
        ///     returned;
        ///     otherwise the default value for the specified type will be returned.
        /// </summary>
        /// <param name="call"></param>
        /// <returns>
        ///     if GetOrAdd or GetOrAddAsync was invoked the unexpected match is set up and the addItemFactory result will be
        ///     returned;
        ///     otherwise the default value for the specified type will be returned if the last method invocation has a return
        ///     type.
        /// </returns>
        public RouteAction Handle(ICall call)
        {
            Logger.LogDebug("NoSetUpHandler invoked");

            var methodInfo = call.GetMethodInfo();
            var args       = call.GetArguments();

            if (methodInfo.Name.Equals("Add"))
            {
                //We have everything we need to set up a match, so let's do it
                var key   = args[0].ToString();
                var value = args[1];

                ProjectReflectionShortcuts.SetUpCacheEntryMethod(value.GetType()).Invoke(null, new[] { _mockedCachingService, key, value });

                return(RouteAction.Return(null));
            }

            if (methodInfo.Name.Equals("GetOrAdd"))
            {
                //We have everything we need to set up a match, so let's do it
                var key   = args[0].ToString();
                var value = args[1].GetType().GetMethod("Invoke").Invoke(args[1], new object[] { new CacheEntryFake(key) });

                ProjectReflectionShortcuts.SetUpCacheEntryMethod(value.GetType()).Invoke(null, new[] { _mockedCachingService, key, value });

                return(RouteAction.Return(value));
            }

            if (methodInfo.Name.Equals("GetOrAddAsync"))
            {
                //We have everything we need to set up a match, so let's do it
                var key        = args[0].ToString();
                var task       = args[1].GetType().GetMethod("Invoke").Invoke(args[1], new object[] { new CacheEntryFake(key) });
                var taskResult = task.GetType().GetProperty("Result").GetValue(task);

                ProjectReflectionShortcuts.SetUpCacheEntryMethod(taskResult.GetType()).Invoke(null, new[] { _mockedCachingService, key, taskResult });

                return(RouteAction.Return(task));
            }

            //void method
            if (methodInfo.ReturnType == typeof(void))
            {
                return(RouteAction.Return(null));
            }

            //Return default values
            if (methodInfo.ReturnType.IsGenericType && methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
            {
                var genericArgument = methodInfo.ReturnType.GetGenericArguments().Single();
                var defaultValue    = genericArgument.GetDefaultValue();

                return(RouteAction.Return(CoreReflectionShortcuts.TaskFromResultMethod(genericArgument).Invoke(null, new[] { defaultValue })));
            }

            return(RouteAction.Return(methodInfo.ReturnType.GetDefaultValue()));
        }
        public RouteAction Handle(ICall call)
        {
            if (_callResults.TryGetResult(call, out var configuredResult))
            {
                return(RouteAction.Return(configuredResult));
            }

            return(RouteAction.Continue());
        }
 private Func <IAutoValueProvider, RouteAction> ReturnValueUsingProvider(ICall call, Type type)
 {
     return(provider =>
     {
         var valueToReturn = provider.GetValue(type);
         ConfigureCall.SetResultForCall(call, new ReturnValue(valueToReturn), MatchArgs.AsSpecifiedInCall);
         return RouteAction.Return(valueToReturn);
     });
 }
Ejemplo n.º 7
0
        public RouteAction Handle(ICall call)
        {
            if (_resultsForType.TryGetResult(call, out var result))
            {
                return(RouteAction.Return(result));
            }

            return(RouteAction.Continue());
        }
Ejemplo n.º 8
0
            public override void Context()
            {
                _call         = mock <ICall>();
                _firstHandler = mock <ICallHandler>();
                _firstHandler.stub(x => x.Handle(_call)).Return(RouteAction.Continue());
                _secondHandler = mock <ICallHandler>();
                _secondHandler.stub(x => x.Handle(_call)).Return(RouteAction.Return(_valueToReturn));

                _handlers = new[] { _firstHandler, _secondHandler };
            }
Ejemplo n.º 9
0
 private Func <IAutoValueProvider, RouteAction> ReturnValueUsingProvider(ICall call, Type type)
 {
     return(provider =>
     {
         var valueToReturn = provider.GetValue(type);
         if (_autoValueBehaviour == AutoValueBehaviour.UseValueForSubsequentCalls)
         {
             ConfigureCall.SetResultForCall(call, new ReturnValue(valueToReturn), MatchArgs.AsSpecifiedInCall);
         }
         return RouteAction.Return(valueToReturn);
     });
 }
Ejemplo n.º 10
0
 private Func <IAutoValueProvider, RouteAction> ReturnValueUsingProvider(ICall call, Type type)
 {
     return(provider =>
     {
         var valueToReturn = provider.GetValue(type);
         if (_autoValueBehaviour == AutoValueBehaviour.UseValueForSubsequentCalls)
         {
             var spec = _callSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall);
             _callResults.SetResult(spec, new ReturnValue(valueToReturn));
         }
         return RouteAction.Return(valueToReturn);
     });
 }
 public RouteAction Handle(ICall call)
 {
     if (ReturnsDynamic(call))
     {
         var stubToReturn = new DynamicStub();
         _configureCall.SetResultForCall(call, new ReturnValue(stubToReturn), MatchArgs.AsSpecifiedInCall);
         return(RouteAction.Return(new DynamicStub()));
     }
     else
     {
         return(RouteAction.Continue());
     }
 }
        public RouteAction Handle(ICall call)
        {
            var type = call.GetReturnType();
            var compatibleProviders = _autoValueProviders.Where(x => x.CanProvideValueFor(type));

            if (compatibleProviders.Any())
            {
                var valueToReturn = compatibleProviders.First().GetValue(type);
                _resultSetter.SetResultForCall(call, new ReturnValue(valueToReturn), MatchArgs.AsSpecifiedInCall);
                return(RouteAction.Return(valueToReturn));
            }
            return(RouteAction.Continue());
        }
Ejemplo n.º 13
0
        public RouteAction Handle(ICall call)
        {
            if (_callResults.TryGetResult(call, out var cachedResult))
            {
                return(RouteAction.Return(cachedResult));
            }

            var type = call.GetReturnType();
            var compatibleProviders = _autoValueProviders.Where(x => x.CanProvideValueFor(type)).FirstOrNothing();

            return(compatibleProviders.Fold(
                       RouteAction.Continue,
                       ReturnValueUsingProvider(call, type)));
        }
Ejemplo n.º 14
0
        public RouteAction Handle(ICall call)
        {
            var methodInfo = call.GetMethodInfo();

            if (methodInfo.Name.Equals("Query") || methodInfo.Name.Equals("Set"))
            {
                throw new InvalidOperationException(string.Format(ExceptionMessages.CannotCreateDbSetTypeNotIncludedInModel, methodInfo.GetGenericArguments().Single().Name));
            }

            if (methodInfo.ReturnType == typeof(void))
            {
                return(RouteAction.Return(null));
            }

            return(RouteAction.Return(methodInfo.ReturnType.GetDefaultValue()));
        }
Ejemplo n.º 15
0
        public void Value_from_custom_handler_is_returned()
        {
            //arrange
            var source = Substitute.For <IValueSource>();
            var router = SubstitutionContext.Current.GetCallRouterFor(source);

            router.RegisterCustomCallHandlerFactory(state =>
                                                    new ActionHandler(
                                                        _ => RouteAction.Return("42")));

            //act
            var result = source.GetValue();

            //assert
            Assert.That(result, Is.EqualTo("42"));
        }
Ejemplo n.º 16
0
            public RouteAction Handle(ICall call)
            {
                var property = call.GetMethodInfo().GetPropertyFromGetterCallOrNull();

                if (property is null)
                {
                    return(RouteAction.Continue());
                }

                var service = _context.ResolveOptional(call.GetReturnType());

                if (service is null)
                {
                    return(RouteAction.Continue());
                }

                return(RouteAction.Return(service));
            }
Ejemplo n.º 17
0
        public void Configured_call_has_more_priority_than_custom_handler()
        {
            //arrange
            var source = Substitute.For <IValueSource>();
            var router = SubstitutionContext.Current.GetCallRouterFor(source);

            router.RegisterCustomCallHandlerFactory(state =>
                                                    new ActionHandler(
                                                        _ => RouteAction.Return("xxx")));

            source.GetValue().Returns("42");

            //act
            var result = source.GetValue();

            //assert
            Assert.That(result, Is.EqualTo("42"));
        }
Ejemplo n.º 18
0
        public void Custom_handler_is_called_for_each_time()
        {
            //arrange
            var source = Substitute.For <IValueSource>();
            var router = SubstitutionContext.Current.GetCallRouterFor(source);

            var values = new Queue <string>(new[] { "42", "10" });

            router.RegisterCustomCallHandlerFactory(state =>
                                                    new ActionHandler(
                                                        _ => RouteAction.Return(values.Dequeue())));

            //act
            var result = source.GetValue();

            result = source.GetValue();

            //assert
            Assert.That(result, Is.EqualTo("10"));
        }
Ejemplo n.º 19
0
        public RouteAction Handle(ICall call)
        {
            if (_callResults.TryGetResult(call, out var cachedResult))
            {
                return(RouteAction.Return(cachedResult));
            }

            var type = call.GetReturnType();

            // This is a hot method which is invoked frequently and has major impact on performance.
            // Therefore, the LINQ cycle was unwinded to loop.
            foreach (var autoValueProvider in _autoValueProviders)
            {
                if (autoValueProvider.CanProvideValueFor(type))
                {
                    return(RouteAction.Return(GetResultValueUsingProvider(call, type, autoValueProvider)));
                }
            }

            return(RouteAction.Continue());
        }
Ejemplo n.º 20
0
 public RouteAction Handle(ICall call)
 {
     return(_resultsForType.HasResultFor(call)
                ? RouteAction.Return(_resultsForType.GetResult(call))
                : RouteAction.Continue());
 }
Ejemplo n.º 21
0
        public RouteAction Handle(ICall call)
        {
            var returnValue = _defaultForType.GetDefaultFor(call.GetMethodInfo().ReturnType);

            return(RouteAction.Return(returnValue));
        }