public TArgument Arg <TArgument>(int index)
        {
            if (index < 0 || index >= _call.GetArguments().Length)
            {
                throw new InvalidOperationException("Method '" + _call.GetMethodInfo().Name + "' do not have that many arguments.");
            }

            if (_call.GetArguments()[index] is TArgument)
            {
                return((TArgument)_call.GetArguments()[index]);
            }

            throw new InvalidOperationException("Argument " + index + " of '" + _call.GetMethodInfo().Name + "' cannot be converted to '" + typeof(TArgument) + "'.");
        }
 public IEnumerable<ArgumentMatchInfo> NonMatchingArguments(ICall call)
 {
     var arguments = call.GetArguments();
     return arguments
             .Select((arg, index) => new ArgumentMatchInfo(index, arg, _argumentSpecifications[index]))
             .Where(x => !x.IsMatch);
 }
Beispiel #3
0
        /// <summary>
        /// Try to handle the call - set ref/out params and return value.
        /// </summary>
        public RouteAction Handle(ICall call)
        {
            if (call == null)
            {
                throw new ArgumentNullException(nameof(call));
            }

            // Don't care about concurrency. If race condition happens - simply use the latest result.
            CallResultData result;

            if (!this.ResultCache.TryGetResult(call, out result))
            {
                result = this.ResultResolver.ResolveResult(call);
                var callSpec = this.CallSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall);

                this.ResultCache.AddResult(callSpec, result);
            }

            var callArguments     = call.GetArguments();
            var originalArguments = call.GetOriginalArguments();

            foreach (var argumentValue in result.ArgumentValues)
            {
                var argIndex = argumentValue.Index;

                // If ref/out value has been already modified (e.g. by When..Do), don't override that value.
                if (!ArgValueWasModified(callArguments[argIndex], originalArguments[argIndex]))
                {
                    callArguments[argIndex] = argumentValue.Value;
                }
            }

            return(result.ReturnValue.Fold(RouteAction.Continue, RouteAction.Return));
        }
        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())));
        }
Beispiel #5
0
        private bool IsSpecifyingACall(ICall call)
        {
            var args     = call.GetArguments() ?? EmptyArgs;
            var argSpecs = call.GetArgumentSpecifications() ?? EmptyArgSpecs;

            return(_isSetToDefaultRoute && args.Any() && argSpecs.Any());
        }
Beispiel #6
0
        private static bool IsSpecifyingACall(ICall call, IRoute currentRoute)
        {
            var args     = call.GetArguments() ?? EmptyArgs;
            var argSpecs = call.GetArgumentSpecifications() ?? EmptyArgSpecs;

            return(currentRoute.IsRecordReplayRoute && args.Any() && argSpecs.Any());
        }
Beispiel #7
0
        public IEnumerable <ArgumentMatchInfo> NonMatchingArguments(ICall call)
        {
            var arguments = call.GetArguments();

            return(arguments
                   .Select((arg, index) => new ArgumentMatchInfo(index, arg, _argumentSpecifications[index]))
                   .Where(x => !x.IsMatch));
        }
 private void If(ICall call, Func<ICall, Predicate<EventInfo>> meetsThisSpecification, Action<string, object> takeThisAction)
 {
     var events = GetEvents(call, meetsThisSpecification);
     if (events.Any())
     {
         takeThisAction(events.First().Name, call.GetArguments()[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()));
        }
Beispiel #10
0
            private string Format(ICall call)
            {
                var methodInfo = call.GetMethodInfo();
                var args       = methodInfo.GetParameters()
                                 .Zip(call.GetArguments(), (p, a) => new ArgAndParamInfo(p, a))
                                 .ToArray();

                return(_callFormatter.Format(methodInfo, FormatArgs(args)));
            }
 public ICallSpecification CreateFrom(ICall call, MatchArgs matchArgs)
 {
     var methodInfo = call.GetMethodInfo();
     var argumentSpecs = call.GetArgumentSpecifications();
     var arguments = call.GetArguments();
     var parameterInfos = call.GetParameterInfos();
     var argumentSpecificationsForCall = _argumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos, matchArgs);
     return new CallSpecification(methodInfo, argumentSpecificationsForCall);
 }
 public IEnumerable<int> NonMatchingArgumentIndicies(ICall call)
 {
     var arguments = call.GetArguments();
     for (var i = 0; i < arguments.Length; i++)
     {
         var argumentMatchesSpecification = ArgIsSpecifiedAndMatchesSpec(arguments[i], i);
         if (!argumentMatchesSpecification) yield return i;
     }
 }
Beispiel #13
0
        private static void If(ICall call, Func <ICall, Predicate <EventInfo> > meetsThisSpecification, Action <string, object> takeThisAction)
        {
            var matchingEvent = GetEvents(call, meetsThisSpecification).FirstOrDefault();

            if (matchingEvent != null)
            {
                takeThisAction(matchingEvent.Name, call.GetArguments()[0]);
            }
        }
        private string FormatCall(ICall call, bool isAcrossMultipleTargets, TypeInstanceNumberLookup instanceLookup)
        {
            var s = _callFormatter.Format(call.GetMethodInfo(), FormatArgs(call.GetArguments()));
            if (!isAcrossMultipleTargets) return s;

            var target = call.Target();
            var methodInfo = call.GetMethodInfo();
            return FormatCallForInstance(instanceLookup, target, methodInfo, s);
        }
        private void If(ICall call, Func <ICall, Predicate <EventInfo> > meetsThisSpecification, Action <string, object> takeThisAction)
        {
            var events = GetEvents(call, meetsThisSpecification);

            if (events.Any())
            {
                takeThisAction(events.First().Name, call.GetArguments()[0]);
            }
        }
 public RouteAction Handle(ICall call)
 {
     if (_propertyHelper.IsCallToSetAReadWriteProperty(call))
     {
         var callToPropertyGetter    = _propertyHelper.CreateCallToPropertyGetterFromSetterCall(call);
         var valueBeingSetOnProperty = call.GetArguments().Last();
         _resultSetter.SetResultForCall(callToPropertyGetter, new ReturnValue(valueBeingSetOnProperty), MatchArgs.AsSpecifiedInCall);
     }
     return(RouteAction.Continue());
 }
 public RouteAction Handle(ICall call)
 {
     if (_propertyHelper.IsCallToSetAReadWriteProperty(call))
     {
         var callToPropertyGetter = _propertyHelper.CreateCallToPropertyGetterFromSetterCall(call);
         var valueBeingSetOnProperty = call.GetArguments().First();
         _resultSetter.SetResultForCall(callToPropertyGetter, new ReturnValue(valueBeingSetOnProperty), MatchArgs.AsSpecifiedInCall);
     }
     return RouteAction.Continue();
 }
 public object Handle(ICall call)
 {
     if (_propertyHelper.IsCallToSetAReadWriteProperty(call))
     {
         var callToPropertyGetter = _propertyHelper.CreateCallToPropertyGetterFromSetterCall(call);
         var valueBeingSetOnProperty = call.GetArguments().First();
         _resultSetter.SetResultForCall(callToPropertyGetter, valueBeingSetOnProperty);
     }
     return null;
 }
Beispiel #19
0
        public ICallSpecification CreateFrom(ICall call, MatchArgs matchArgs)
        {
            var methodInfo     = call.GetMethodInfo();
            var argumentSpecs  = call.GetArgumentSpecifications();
            var arguments      = call.GetArguments();
            var parameterInfos = call.GetParameterInfos();
            var argumentSpecificationsForCall = _argumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos, matchArgs);

            return(new CallSpecification(methodInfo, argumentSpecificationsForCall));
        }
        private static IEnumerable<Argument> GetArgumentsFromCall(ICall call)
        {
            var values = call.GetArguments();
            var types = call.GetParameterInfos().Select(x => x.ParameterType).ToArray();

            for (var index = 0; index < values.Length; index++)
            {
                var i = index;
                yield return new Argument(types[i], () => values[i], x => values[i] = x);
            }
        }
Beispiel #21
0
        private static string DumpCallInfo(ICall cur)
        {
            var methodName = cur.GetMethodInfo().Name;
            var args       = cur.GetArguments()
                             .Select(a => a is string
                                     ?$"\"{a}\""
                                     : a)
                             .JoinWith(", ");

            return($"{methodName}({args})");
        }
Beispiel #22
0
        private static IEnumerable <Argument> GetArgumentsFromCall(ICall call)
        {
            var values         = call.GetArguments();
            var parameterInfos = call.GetParameterInfos();

            for (var index = 0; index < values.Length; index++)
            {
                var i = index;
                yield return(new Argument(parameterInfos[i].ParameterType, () => values[i], x => values[i] = x));
            }
        }
        private static IEnumerable <Argument> GetArgumentsFromCall(ICall call)
        {
            var values = call.GetArguments();
            var types  = call.GetParameterInfos().Select(x => x.ParameterType).ToArray();

            for (var index = 0; index < values.Length; index++)
            {
                var i = index;
                yield return(new Argument(types[i], () => values[i], x => values[i] = x));
            }
        }
 public bool IsSatisfiedBy(ICall call)
 {
     if (MethodInfo != call.GetMethodInfo()) return false;
     var arguments = call.GetArguments();
     if (arguments.Length != ArgumentSpecifications.Count) return false;
     for (int i = 0; i < arguments.Length; i++)
     {
         var argumentMatchesSpecification = ArgumentSpecifications[i].IsSatisfiedBy(arguments[i]);
         if (!argumentMatchesSpecification) return false;
     }
     return true;
 }
 public ICall CreateCallToPropertyGetterFromSetterCall(ICall callToSetter)
 {
     var propertyInfo = GetPropertyFromSetterCallOrNull(callToSetter);
     if (!PropertySetterExistsAndHasAGetMethod(propertyInfo))
     {
         throw new InvalidOperationException("Could not find a GetMethod for \"" + callToSetter.GetMethodInfo() + "\"");
     }
     var setterArgs = callToSetter.GetArguments();
     var getter = propertyInfo.GetGetMethod();
     var getterArgs = setterArgs.Take(setterArgs.Length - 1).ToArray();
     return new Call(getter, getterArgs, callToSetter.Target(), callToSetter.GetArgumentSpecifications());
 }
Beispiel #26
0
            static bool LogOneWarning(ICall call)
            {
                if (call.GetMethodInfo().Name != "Log")
                {
                    return(false);
                }

                var args      = call.GetArguments();
                var logLevel  = (LogLevel)args[0];
                var exception = (Exception)args[3];

                return(logLevel == LogLevel.Warning && exception.Message.Contains("null"));
            }
Beispiel #27
0
        /// <summary>
        /// Gets a notification if one was scheduled.
        /// </summary>
        /// <returns>The scheduled notification.</returns>
        public ScheduledNotification <Guid> GetScheduledNotification()
        {
            ICall saveScheduledNotification =
                this.NotificationRepository
                .ReceivedCalls()
                .SingleOrDefault(call => call.GetMethodInfo().Name == nameof(INotificationRepository <Guid> .SaveScheduledNotification));

            if (saveScheduledNotification == null)
            {
                throw new InvalidOperationException("A notification was not scheduled.");
            }

            return(saveScheduledNotification.GetArguments().Cast <ScheduledNotification <Guid> >().Single());
        }
Beispiel #28
0
        public ICall CreateCallToPropertyGetterFromSetterCall(ICall callToSetter)
        {
            var propertyInfo = GetPropertyFromSetterCallOrNull(callToSetter);

            if (!PropertySetterExistsAndHasAGetMethod(propertyInfo))
            {
                throw new InvalidOperationException("Could not find a GetMethod for \"" + callToSetter.GetMethodInfo() + "\"");
            }
            var setterArgs = callToSetter.GetArguments();
            var getter     = propertyInfo.GetGetMethod();
            var getterArgs = setterArgs.Take(setterArgs.Length - 1).ToArray();

            return(new Call(getter, getterArgs, callToSetter.Target(), callToSetter.GetArgumentSpecifications()));
        }
Beispiel #29
0
        public ICall CreateCallToPropertyGetterFromSetterCall(ICall callToSetter)
        {
            var propertyInfo = GetPropertyFromSetterCallOrNull(callToSetter);

            if (!PropertySetterExistsAndHasAGetMethod(propertyInfo))
            {
                throw new InvalidOperationException("Could not find a GetMethod for \"" + callToSetter.GetMethodInfo() + "\"");
            }

            var getter     = propertyInfo.GetGetMethod();
            var getterArgs = SkipLast(callToSetter.GetArguments());
            var getterArgumentSpecifications = GetGetterCallSpecificationsFromSetterCall(callToSetter);

            return(_callFactory.Create(getter, getterArgs, callToSetter.Target(), getterArgumentSpecifications));
        }
Beispiel #30
0
    /// <summary>
    /// Validate a call to <see cref="IFluentQuery{TEntity, TId}.Where(string, object)"/>
    /// </summary>
    /// <param name="call">Call</param>
    /// <param name="expectedClause">Expected clause</param>
    /// <param name="expectedParameters">Expected parameters</param>
    public static void AssertWhere(ICall call, string expectedClause, object expectedParameters)
    {
        // Check the method name
        AssertMethodName(call, nameof(IFake.Where));

        // Check the parameters
        AssertCollection(call.GetArguments(),

                         // Check that the correct clause is being used
                         actualClause => AssertEqualType(expectedClause, actualClause),

                         // Check that the correct parameters are being used -
                         // using Json serialisation to support anonymous types
                         actualParameters => AssertEqualJson(expectedParameters, actualParameters)
                         );
    }
Beispiel #31
0
            private bool CallArgsWere(ICall call, object[] expectedArguments)
            {
                var callArguments = call.GetArguments();

                if (callArguments.Length != expectedArguments.Length)
                {
                    return(false);
                }
                for (int i = 0; i < callArguments.Length; i++)
                {
                    if (!callArguments[i].Equals(expectedArguments[i]))
                    {
                        return(false);
                    }
                }
                return(true);
            }
Beispiel #32
0
    /// <summary>
    /// Validate a call to <see cref="IFluentQuery{TEntity, TId}.Sort{TValue}(Expression{Func{TEntity, TValue}}, SortOrder)"/>
    /// </summary>
    /// <typeparam name="TEntity">Entity type</typeparam>
    /// <typeparam name="TValue">Column select value type</typeparam>
    /// <param name="call">Call</param>
    /// <param name="expectedProperty">Expected property</param>
    /// <param name="expectedOrder">Expected sort order</param>
    public static void AssertSort <TEntity, TValue>(ICall call, string expectedProperty, SortOrder expectedOrder)
    {
        // Check the method
        AssertMethodName(call, nameof(IFake.Sort));

        // Check the generic arguments
        AssertGenericArgument <TValue>(call);

        // Check each predicate
        Assert.Collection(call.GetArguments(),

                          // Check that the correct property is being used
                          actualProperty => AssertPropertyExpression <TEntity, TValue>(expectedProperty, actualProperty),

                          // Check that the correct order is being used
                          actualCompare => AssertEqualType(expectedOrder, actualCompare)
                          );
    }
Beispiel #33
0
    /// <summary>
    /// Validate a call to <see cref="IFluentQuery{TEntity, TId}.WhereNotIn{TValue}(Expression{Func{TEntity, TValue}}, IEnumerable{TValue})"/>
    /// </summary>
    /// <typeparam name="TEntity">Entity type</typeparam>
    /// <typeparam name="TValue">Column select value type</typeparam>
    /// <param name="call">Call</param>
    /// <param name="expectedProperty">Expected property</param>
    /// <param name="expectedValues">Expected values</param>
    public static void AssertWhereNotIn <TEntity, TValue>(ICall call, string expectedProperty, TValue[] expectedValues)
    {
        // Check the method
        AssertMethodName(call, nameof(IFake.WhereNotIn));

        // Check the generic arguments
        AssertGenericArgument <TValue>(call);

        // Check each parameters
        AssertCollection(call.GetArguments(),

                         // Check that the correct property is being used
                         actualProperty => AssertPropertyExpression <TEntity, TValue>(expectedProperty, actualProperty),

                         // Check that the correct values are being used
                         actualValue => AssertEqualType(expectedValues, actualValue)
                         );
    }
Beispiel #34
0
            public override void Context()
            {
                base.Context();
                var methodInfo = ReflectionHelper.GetMethod(() => SampleMethod());
                var arguments  = new[] { new object() };

                _call = CreateStubCall(methodInfo, arguments);
                _call.stub(x => x.GetArgumentSpecifications()).Return(mock <IList <IArgumentSpecification> >());

                _argumentSpecificationsFactory = mock <IArgumentSpecificationsFactory>();
                _argSpecsFromFactory           = new[] { mock <IArgumentSpecification>(), mock <IArgumentSpecification>() };
                _argumentSpecificationsFactory
                .Stub(x => x.Create(
                          _call.GetArgumentSpecifications(),
                          _call.GetArguments(),
                          _call.GetParameterInfos(),
                          _argMatching))
                .Return(_argSpecsFromFactory);
            }
        private static void AssertCalculateCall(ICall call,
                                                BalancedFieldLengthCalculation calculation,
                                                int failureVelocity)
        {
            object[] arguments = call.GetArguments();
            AircraftDataTestHelper.AssertAircraftData(calculation.AircraftData,
                                                      calculation.EngineData,
                                                      (KernelAircraftData)arguments[0]);

            Assert.That(arguments[1], Is.TypeOf <EulerIntegrator>());

            GeneralSimulationSettingsData simulationSettings = calculation.SimulationSettings;

            Assert.That(arguments[2], Is.EqualTo(calculation.EngineData.NrOfFailedEngines));
            Assert.That(arguments[3], Is.EqualTo(simulationSettings.Density));
            Assert.That(arguments[4], Is.EqualTo(simulationSettings.GravitationalAcceleration));

            CalculationSettingsTestHelper.AssertCalculationSettings(simulationSettings, failureVelocity,
                                                                    (CalculationSettings)arguments[5]);
        }
 public ICallSpecification CreateFrom(ICall call)
 {
     var result = new CallSpecification(call.GetMethodInfo());
     var argumentSpecs = _context.DequeueAllArgumentSpecifications();
     var arguments = call.GetArguments();
     if (argumentSpecs.Count == 0)
     {
         AddArgumentSpecsToCallSpec(result, arguments.Select(x => (IArgumentSpecification) new ArgumentEqualsSpecification(x)));
     }
     else if (argumentSpecs.Count == arguments.Length)
     {
         AddArgumentSpecsToCallSpec(result, argumentSpecs);
     }
     else
     {
         throw new AmbiguousArgumentsException(
             "Cannot determine argument specifications to use. Please use specifications for all arguments.");
     }
     return result;
 }
        public void Validate_Always_FactoryReceiveCorrectData()
        {
            // Setup
            var calculation = new BalancedFieldLengthCalculation();

            SetValidAircraftData(calculation.AircraftData);
            SetEngineData(calculation.EngineData);
            SetSimulationSettingsData(calculation.SimulationSettings);

            var kernel = Substitute.For <IAggregatedDistanceCalculatorKernel>();

            kernel.Validate(Arg.Any <KernelAircraftData>(),
                            Arg.Any <double>(),
                            Arg.Any <double>(),
                            Arg.Any <int>())
            .ReturnsForAnyArgs(KernelValidationError.None);

            var testFactory = new TestKernelFactory(kernel);

            using (new BalancedFieldLengthKernelFactoryConfig(testFactory))
            {
                var module = new BalancedFieldLengthCalculationModule();

                // Call
                module.Validate(calculation);

                // Assert
                ICall    calls     = kernel.ReceivedCalls().Single();
                object[] arguments = calls.GetArguments();
                AircraftDataTestHelper.AssertAircraftData(calculation.AircraftData,
                                                          calculation.EngineData,
                                                          (KernelAircraftData)arguments[0]);

                GeneralSimulationSettingsData simulationSettings = calculation.SimulationSettings;
                Assert.That(arguments[1], Is.EqualTo(simulationSettings.Density));
                Assert.That(arguments[2], Is.EqualTo(simulationSettings.GravitationalAcceleration));
                Assert.That(arguments[3], Is.EqualTo(calculation.EngineData.NrOfFailedEngines));
            }
        }
    /// <summary>
    /// Validate a call to <see cref="IFluentQuery{TEntity, TId}.ExecuteAsync{TValue}(Expression{Func{TEntity, TValue}})"/>
    /// </summary>
    /// <typeparam name="TEntity">Entity type</typeparam>
    /// <typeparam name="TValue">Column select value type</typeparam>
    /// <param name="call">Call</param>
    /// <param name="expected">Expected property</param>
    /// <param name="withTransaction">Whether or not to check for a transaction</param>
    public static void AssertExecute <TEntity, TValue>(ICall call, string expected, bool withTransaction)
    {
        // Check the method name
        AssertMethodName(call, nameof(IFake.ExecuteAsync));

        // Check the generic arguments
        AssertGenericArgument <TValue>(call);

        // Check the parameters
        var inspectors = new List <Action <object?> >
        {
            // Check that the correct property is being used
            { actualProperty => AssertPropertyExpression <TEntity, TValue>(expected, actualProperty) }
        };

        if (withTransaction)
        {
            // Use discard as a placeholder so the right number of items is checked in the collection
            inspectors.Add(_ => { });
        }

        AssertCollection(call.GetArguments(), inspectors.ToArray());
    }
Beispiel #39
0
    /// <summary>
    /// Validate a call to <see cref="IFluentQuery{TEntity, TId}.Where{TValue}(Expression{Func{TEntity, TValue}}, Compare, TValue)"/>
    /// </summary>
    /// <typeparam name="TEntity">Entity type</typeparam>
    /// <typeparam name="TValue">Column select value type</typeparam>
    /// <param name="call">Call</param>
    /// <param name="expectedProperty">Expected property</param>
    /// <param name="expectedCompare">Expected comparison</param>
    /// <param name="expectedValue">Expected value</param>
    public static void AssertWhere <TEntity, TValue>(
        ICall call,
        string expectedProperty,
        Compare expectedCompare,
        TValue expectedValue
        )
    {
        // Check the method name
        AssertMethodName(call, nameof(IFake.Where));

        // Check the generic arguments
        AssertGenericArgument <TValue>(call);

        // Check the parameters
        AssertCollection(call.GetArguments(),

                         // Check that the correct property is being used
                         actualProperty => AssertPropertyExpression <TEntity, TValue>(expectedProperty, actualProperty),

                         // Check that the correct compare is being used
                         actualCompare => AssertEqualType(expectedCompare, actualCompare),

                         // Check that the correct value is being used
                         actualValue =>
        {
            if (actualValue is null)
            {
                Assert.Null(actualValue);
            }
            else
            {
                AssertEqual(expectedValue, actualValue);
            }
        }
                         );
    }
Beispiel #40
0
 public void Should_set_required_call_properties()
 {
     Assert.That(_result.GetMethodInfo(), Is.EqualTo(_method));
     Assert.That(_result.GetArguments(), Is.EqualTo(_args));
     Assert.That(_result.Target(), Is.SameAs(_target));
 }
Beispiel #41
0
 public string Format(ICall call, ICallSpecification withRespectToCallSpec)
 {
     return Format(call.GetMethodInfo(), call.GetArguments(), withRespectToCallSpec.NonMatchingArgumentIndicies(call));
 }
 public static T Arg <T>(this ICall call, int index)
 {
     return((T)call.GetArguments()[index]);
 }
 private bool HasDifferentNumberOfArguments(ICall call)
 {
     return _argumentSpecifications.Length != call.GetArguments().Length;
 }
 private string Format(ICall call)
 {
     return _callFormatter.Format(call.GetMethodInfo(), FormatArgs(call.GetArguments()));
 }
Beispiel #45
0
 public object Handle(ICall call)
 {
     _actionToPerform(call.GetArguments());
     return null;
 }
Beispiel #46
0
 private bool IsSpecifyingACall(ICall call)
 {
     var args = call.GetArguments() ?? EmptyArgs;
     var argSpecs = call.GetArgumentSpecifications() ?? EmptyArgSpecs;
     return _isSetToDefaultRoute && args.Any() && argSpecs.Any();
 }
 public string Format(ICall call)
 {
     return CallFormatter.Format(call.GetMethodInfo(), FormatArguments(call.GetArguments()));
 }