Beispiel #1
0
        public void AreDifferentTypesShouldReturnTrueWithObjectsOfDifferentTypes()
        {
            var first  = 0;
            var second = "Test";

            Assert.True(Reflection.AreDifferentTypes(first, second));
        }
Beispiel #2
0
        public void AreDifferentTypesShouldReturnFalseWithSameTypes()
        {
            var first  = typeof(List <>);
            var second = typeof(List <>);

            Assert.False(Reflection.AreDifferentTypes(first, second));
        }
Beispiel #3
0
        public void AreDifferentTypesShouldReturnTrueWithDifferentTypes()
        {
            var first  = typeof(int);
            var second = typeof(string);

            Assert.True(Reflection.AreDifferentTypes(first, second));
        }
Beispiel #4
0
        public void AreDifferentTypesShouldReturnFalseWithInheritedTypes()
        {
            var first  = typeof(List <>);
            var second = typeof(IEnumerable <>);

            Assert.True(Reflection.AreDifferentTypes(first, second));
        }
        /// <summary>
        /// Tests internal server error whether it contains exception with the same type and having the same message as the provided exception.
        /// </summary>
        /// <param name="exception">Expected exception.</param>
        /// <returns>Exception test builder.</returns>
        public IBaseTestBuilderWithCaughtException WithException(Exception exception)
        {
            var exceptionResult = this.GetExceptionResult();
            var actualException = exceptionResult.Exception;

            if (Reflection.AreDifferentTypes(actualException, exception))
            {
                throw new InternalServerErrorResultAssertionException(string.Format(
                                                                          "When calling {0} action in {1} expected internal server error result to contain {2}, but instead received {3}.",
                                                                          this.ActionName,
                                                                          this.Controller.GetName(),
                                                                          exception.GetName(),
                                                                          actualException.GetName()));
            }

            var expectedExceptionMessage = exception.Message;
            var actualExceptionMessage   = actualException.Message;

            if (expectedExceptionMessage != actualExceptionMessage)
            {
                throw new InternalServerErrorResultAssertionException(string.Format(
                                                                          "When calling {0} action in {1} expected internal server error result to contain exception with message '{2}', but instead received '{3}'.",
                                                                          this.ActionName,
                                                                          this.Controller.GetName(),
                                                                          expectedExceptionMessage,
                                                                          actualExceptionMessage));
            }

            return(this.NewAndProvideTestBuilder());
        }
        private void ValidateActionReturnType(Type typeOfExpectedReturnValue, bool canBeAssignable = false, bool allowDifferentGenericTypeDefinitions = false)
        {
            CommonValidator.CheckForException(this.CaughtException);

            var typeInfoOfExpectedReturnValue = typeOfExpectedReturnValue.GetTypeInfo();

            var typeOfActionResult = this.ActionResult?.GetType();

            if (typeOfActionResult == null)
            {
                this.ThrowNewGenericActionResultAssertionException(
                    typeOfExpectedReturnValue.ToFriendlyTypeName(),
                    "null");
            }

            var typeInfoOfActionResult = typeOfActionResult.GetTypeInfo();

            var isAssignableCheck = canBeAssignable && Reflection.AreNotAssignable(typeOfExpectedReturnValue, typeOfActionResult);

            if (isAssignableCheck && allowDifferentGenericTypeDefinitions &&
                Reflection.IsGeneric(typeOfExpectedReturnValue) && Reflection.IsGenericTypeDefinition(typeOfExpectedReturnValue))
            {
                isAssignableCheck = Reflection.AreAssignableByGeneric(typeOfExpectedReturnValue, typeOfActionResult);

                if (!isAssignableCheck && !typeInfoOfActionResult.IsGenericType)
                {
                    isAssignableCheck = true;
                }
                else
                {
                    isAssignableCheck =
                        !Reflection.ContainsGenericTypeDefinitionInterface(typeOfExpectedReturnValue, typeOfActionResult);
                }
            }

            var strictlyEqualCheck = !canBeAssignable && Reflection.AreDifferentTypes(typeOfExpectedReturnValue, typeOfActionResult);

            var invalid = isAssignableCheck || strictlyEqualCheck;

            if (invalid && typeInfoOfExpectedReturnValue.IsGenericTypeDefinition && typeInfoOfActionResult.IsGenericType)
            {
                var actionResultGenericDefinition = typeInfoOfActionResult.GetGenericTypeDefinition();
                if (actionResultGenericDefinition == typeOfExpectedReturnValue)
                {
                    invalid = false;
                }
            }

            if (invalid && typeInfoOfExpectedReturnValue.IsGenericType && typeInfoOfActionResult.IsGenericType)
            {
                invalid = !Reflection.AreAssignableByGeneric(typeOfExpectedReturnValue, typeOfActionResult);
            }

            if (invalid)
            {
                this.ThrowNewGenericActionResultAssertionException(
                    typeOfExpectedReturnValue.ToFriendlyTypeName(),
                    typeOfActionResult.ToFriendlyTypeName());
            }
        }
Beispiel #7
0
        private void ValidateRouteInformation <TController>()
        {
            var expectedRouteValues = this.GetExpectedRouteInfo();
            var actualRouteValues   = this.GetActualRouteInfo();

            if (!actualRouteValues.IsResolved)
            {
                this.ThrowNewRouteAssertionException(actual: actualRouteValues.UnresolvedError);
            }

            var expectedControllerType = this.expectedRouteInfo.ControllerType;
            var actualControllerType   = this.actualRouteInfo.ControllerType.AsType();

            if (Reflection.AreDifferentTypes(expectedControllerType, actualControllerType))
            {
                this.ThrowNewRouteAssertionException(actual: string.Format(
                                                         "instead matched {0}",
                                                         actualControllerType.ToFriendlyTypeName()));
            }

            if (expectedRouteValues.Action != actualRouteValues.Action)
            {
                this.ThrowNewRouteAssertionException(actual: string.Format(
                                                         "instead matched {0} action",
                                                         actualRouteValues.Action));
            }

            expectedRouteValues.ActionArguments.ForEach(arg => this.ToRouteValue(arg.Key, arg.Value.Value));
        }
Beispiel #8
0
        public void AreDifferentTypesShouldReturnFalseWithObjectsOfSameTypes()
        {
            var first  = 1;
            var second = 2;

            Assert.False(Reflection.AreDifferentTypes(first, second));
        }
Beispiel #9
0
        private void ValidateRouteInformation <TController>()
            where TController : ApiController
        {
            var expectedRouteValues = this.GetExpectedRouteInfo <TController>();
            var actualRouteValues   = this.GetActualRouteInfo();

            if (!actualRouteValues.IsResolved)
            {
                this.ThrowNewRouteAssertionException(actual: actualRouteValues.UnresolvedError);
            }

            if (actualRouteValues.IsIgnored)
            {
                this.ThrowNewRouteAssertionException(actual: "it was ignored with StopRoutingHandler");
            }

            if (Reflection.AreDifferentTypes(this.expectedRouteInfo.Controller, this.actualRouteInfo.Controller))
            {
                this.ThrowNewRouteAssertionException(actual: string.Format(
                                                         "instead matched {0}",
                                                         actualRouteValues.Controller.ToFriendlyTypeName()));
            }

            if (expectedRouteValues.Action != actualRouteValues.Action)
            {
                this.ThrowNewRouteAssertionException(actual: string.Format(
                                                         "instead matched {0} action",
                                                         actualRouteValues.Action));
            }

            expectedRouteValues.Arguments.ForEach(arg =>
            {
                if (arg.Value.Value != null && arg.Value.Value.ToString() == ExpressionParser.IgnoredArgument)
                {
                    return;
                }

                if (!actualRouteValues.ActionArguments.ContainsKey(arg.Key))
                {
                    this.ThrowNewRouteAssertionException(actual: string.Format(
                                                             "the '{0}' parameter could not be found",
                                                             arg.Key));
                }

                var expectedArgumentInfo = arg.Value;
                var actualArgumentInfo   = actualRouteValues.ActionArguments[arg.Key];
                if (Reflection.AreNotDeeplyEqual(expectedArgumentInfo.Value, actualArgumentInfo.Value))
                {
                    this.ThrowNewRouteAssertionException(actual: string.Format(
                                                             "the '{0}' parameter was different",
                                                             arg.Key));
                }
            });
        }
        /// <inheritdoc />
        public IAndJsonSerializerSettingsTestBuilder WithEqualityComparerOfType(Type equalityComparerType)
        {
            this.validations.Add((expected, actual) =>
            {
                if (Reflection.AreDifferentTypes(equalityComparerType, actual.EqualityComparer?.GetType()))
                {
                    this.ThrowNewJsonResultAssertionException(
                        $"equality comparer of {equalityComparerType.ToFriendlyTypeName()} type",
                        $"in fact found {actual.EqualityComparer.GetName()}");
                }
            });

            return(this);
        }
        /// <inheritdoc />
        public IAndJsonSerializerSettingsTestBuilder WithContractResolverOfType(Type contractResolverType)
        {
            this.validations.Add((expected, actual) =>
            {
                if (Reflection.AreDifferentTypes(contractResolverType, actual.ContractResolver?.GetType()))
                {
                    this.ThrowNewJsonResultAssertionException(
                        $"{contractResolverType.ToFriendlyTypeName()}",
                        $"in fact found {actual.ContractResolver.GetName()}");
                }
            });

            return(this);
        }
        /// <inheritdoc />
        public IAndJsonSerializerSettingsTestBuilder ContainingConverterOfType(Type jsonConverterType)
        {
            this.validations.Add((expected, actual) =>
            {
                if (actual.Converters.All(c => Reflection.AreDifferentTypes(c.GetType(), jsonConverterType)))
                {
                    this.ThrowNewJsonResultAssertionException(
                        $"converter of {jsonConverterType.Name} type",
                        "such was not found");
                }
            });

            return(this);
        }
Beispiel #13
0
        /// <summary>
        /// Tests the ContractResolver property in a JSON serializer settings object.
        /// </summary>
        /// <param name="contractResolver">Expected ContractResolver.</param>
        /// <returns>The same JSON serializer settings test builder.</returns>
        public IAndJsonSerializerSettingsTestBuilder WithContractResolver(IContractResolver contractResolver)
        {
            this.jsonSerializerSettings.ContractResolver = contractResolver;
            this.validations.Add((expected, actual) =>
            {
                if (Reflection.AreDifferentTypes(expected.ContractResolver, actual.ContractResolver))
                {
                    this.ThrowNewJsonResultAssertionException(
                        string.Format("{0}", expected.ContractResolver.GetName()),
                        string.Format("in fact found {0}", actual.ContractResolver.GetName()));
                }
            });

            return(this);
        }
        /// <summary>
        /// Validates whether object result Formatters contains the provided type of output formatter.
        /// </summary>
        /// <typeparam name="TOutputFormatter">Type of expected output formatter.</typeparam>
        /// <param name="objectResult">Object result to test.</param>
        /// <param name="failedValidationAction">Action to call in case of failed validation.</param>
        public static void ValidateContainingOutputFormatterOfType <TOutputFormatter>(
            ObjectResult objectResult,
            Action <string, string, string> failedValidationAction)
        {
            var outputFormatters = objectResult.Formatters;
            var typeOfExpectedOutputFormatter = typeof(TOutputFormatter);

            if (outputFormatters.All(f => Reflection.AreDifferentTypes(f.GetType(), typeOfExpectedOutputFormatter)))
            {
                failedValidationAction(
                    "output formatters",
                    $"to contain formatter of {typeOfExpectedOutputFormatter.Name} type",
                    "such was not found");
            }
        }
        /// <summary>
        /// Validates whether object result Formatters contains the provided type of output formatter.
        /// </summary>
        /// <param name="objectResult">Object result to test.</param>
        /// <param name="failedValidationAction">Action to call in case of failed validation.</param>
        /// <param name="outputFromatterType"></param>
        public static void ValidateContainingOutputFormatterOfType(
            ObjectResult objectResult,
            Action <string, string, string> failedValidationAction,
            Type outputFromatterType)
        {
            var outputFormatters = objectResult.Formatters;

            if (outputFormatters.All(f => Reflection.AreDifferentTypes(f.GetType(), outputFromatterType)))
            {
                failedValidationAction(
                    "output formatters",
                    $"to contain formatter of {outputFromatterType.Name} type",
                    "such was not found");
            }
        }
        /// <inheritdoc />
        public IAndJsonSerializerSettingsTestBuilder WithReferenceResolverOfType(Type referenceResolverType)
        {
            this.validations.Add((expected, actual) =>
            {
                var actualReferenceResolverType = actual.ReferenceResolverProvider()?.GetType();
                if (Reflection.AreDifferentTypes(referenceResolverType, actualReferenceResolverType))
                {
                    this.ThrowNewJsonResultAssertionException(
                        $"reference resolver of {referenceResolverType.ToFriendlyTypeName()} type",
                        $"in fact found {actualReferenceResolverType.ToFriendlyTypeName()}");
                }
            });

            return(this);
        }
        /// <inheritdoc />
        public IAndJsonSerializerSettingsTestBuilder WithTraceWriterOfType(Type traceWriterType)
        {
            this.validations.Add((expected, actual) =>
            {
                var actualTraceWriterType = actual.TraceWriter?.GetType();
                if (Reflection.AreDifferentTypes(traceWriterType, actualTraceWriterType))
                {
                    this.ThrowNewJsonResultAssertionException(
                        $"trace writer of {traceWriterType.ToFriendlyTypeName()} type",
                        $"in fact found {actualTraceWriterType.ToFriendlyTypeName()}");
                }
            });

            return(this);
        }
        /// <inheritdoc />
        public IAndMemoryCacheTestBuilder ContainingEntryOfType <TEntry>(object key)
        {
            var value        = this.GetValue(key);
            var expectedType = typeof(TEntry);
            var actualType   = value.GetType();

            if (Reflection.AreDifferentTypes(expectedType, actualType))
            {
                this.ThrowNewDataProviderAssertionException(
                    MemoryCacheName,
                    $"to have entry with the given key and value of {expectedType.ToFriendlyTypeName()} type",
                    $"in fact found {actualType.ToFriendlyTypeName()}");
            }

            return(this);
        }
Beispiel #19
0
        /// <inheritdoc />
        public IAndExceptionTestBuilder OfType <TException>()
        {
            var expectedExceptionType = typeof(TException);
            var actualExceptionType   = this.TestContext.CaughtException.GetType();

            if (Reflection.AreDifferentTypes(expectedExceptionType, actualExceptionType))
            {
                throw new InvalidExceptionAssertionException(string.Format(
                                                                 "{0} {1}, but instead received {2}.",
                                                                 this.TestContext.ExceptionMessagePrefix,
                                                                 expectedExceptionType.ToFriendlyTypeName(),
                                                                 actualExceptionType.ToFriendlyTypeName()));
            }

            return(this);
        }
Beispiel #20
0
        /// <inheritdoc />
        public IAndResolvedRouteTestBuilder To <TController>()
            where TController : class
        {
            var actualInfo             = this.GetActualRouteInfo();
            var expectedControllerType = typeof(TController);
            var actualControllerType   = actualInfo.ControllerType.AsType();

            if (Reflection.AreDifferentTypes(expectedControllerType, actualControllerType))
            {
                this.ThrowNewRouteAssertionException(
                    $"match {expectedControllerType.ToFriendlyTypeName()}",
                    $"in fact matched {actualControllerType.ToFriendlyTypeName()}");
            }

            return(this);
        }
Beispiel #21
0
        /// <summary>
        /// Tests whether the content of the HTTP response message is of certain type.
        /// </summary>
        /// <typeparam name="TContentType">Type of expected HTTP content.</typeparam>
        /// <returns>The same HTTP response message test builder.</returns>
        public IAndHttpResponseMessageTestBuilder WithContentOfType <TContentType>()
            where TContentType : HttpContent
        {
            var expectedType = typeof(TContentType);
            var actualType   = this.ActionResult.Content.GetType();

            if (Reflection.AreDifferentTypes(expectedType, actualType))
            {
                this.ThrowNewHttpResponseMessageAssertionException(
                    "content",
                    string.Format("to be {0}", expectedType.ToFriendlyTypeName()),
                    string.Format("was in fact {0}", actualType.ToFriendlyTypeName()));
            }

            return(this);
        }
        protected virtual void ValidateType(Type type, Func <TAttribute, Type> getTypeValueFunc)
        {
            this.Attribute = (TAttribute)Activator.CreateInstance(typeof(TAttribute), type);
            this.Validations.Add((expected, actual) =>
            {
                var expectedType = getTypeValueFunc(expected);
                var actualType   = getTypeValueFunc(actual);

                if (Reflection.AreDifferentTypes(expectedType, actualType))
                {
                    this.FailedValidationAction(
                        $"{this.ExceptionMessagePrefix}'{expectedType.ToFriendlyTypeName()}' type",
                        $"in fact found '{actualType.ToFriendlyTypeName()}'");
                }
            });
        }
        /// <inheritdoc />
        public IAndViewTestBuilder WithViewEngineOfType <TViewEngine>()
            where TViewEngine : IViewEngine
        {
            var actualViewEngine = this.GetViewEngine();

            if (actualViewEngine == null ||
                Reflection.AreDifferentTypes(typeof(TViewEngine), actualViewEngine.GetType()))
            {
                this.ThrowNewViewResultAssertionException(
                    "ViewEngine",
                    $"to be of {typeof(TViewEngine).Name} type",
                    $"instead received {actualViewEngine.GetName()}");
            }

            return(this);
        }
Beispiel #24
0
 /// <summary>
 /// Validates the Formatters from action result containing one.
 /// </summary>
 /// <param name="actionResult">Action result with Formatters.</param>
 /// <param name="mediaTypeFormatter">Expected MediaTypeFormatter.</param>
 /// <param name="failedValidationAction">Action to call in case of failed validation.</param>
 public static void ValidateMediaTypeFormatter(
     dynamic actionResult,
     MediaTypeFormatter mediaTypeFormatter,
     Action <string, string, string> failedValidationAction)
 {
     RuntimeBinderValidator.ValidateBinding(() =>
     {
         var formatters = TryGetMediaTypeFormatters(actionResult) as IEnumerable <MediaTypeFormatter>;
         if (formatters == null || formatters.All(f => Reflection.AreDifferentTypes(f, mediaTypeFormatter)))
         {
             failedValidationAction(
                 "Formatters",
                 string.Format("to contain {0}", mediaTypeFormatter.GetName()),
                 "none was found");
         }
     });
 }
 /// <summary>
 /// Validates the IContentNegotiator from action result containing one.
 /// </summary>
 /// <param name="actionResult">Action result with IContentNegotiator.</param>
 /// <param name="contentNegotiator">Expected IContentNegotiator.</param>
 /// <param name="failedValidationAction">Action to call in case of failed validation.</param>
 public static void ValidateContentNegotiator(
     dynamic actionResult,
     IContentNegotiator contentNegotiator,
     Action <string, string, string> failedValidationAction)
 {
     RuntimeBinderValidator.ValidateBinding(() =>
     {
         var actualContentNegotiator = actionResult.ContentNegotiator as IContentNegotiator;
         if (Reflection.AreDifferentTypes(contentNegotiator, actualContentNegotiator))
         {
             failedValidationAction(
                 "IContentNegotiator",
                 string.Format("to be {0}", contentNegotiator.GetName()),
                 string.Format("instead received {0}", actualContentNegotiator.GetName()));
         }
     });
 }
        /// <inheritdoc />
        public IAndDataProviderEntryDetailsTestBuilder <TValue> WithValueOfType <TValue>()
        {
            this.validations.Add((actual) =>
            {
                var expectedType = typeof(TValue);
                var actualType   = actual.GetType();

                if (Reflection.AreDifferentTypes(expectedType, actualType))
                {
                    this.ThrowNewDataProviderAssertionException(
                        $"to have entry with '{this.entryKey}' key and value of {expectedType.ToFriendlyTypeName()} type",
                        $"in fact found {actualType.ToFriendlyTypeName()}");
                }
            });

            return(new DataProviderEntryDetailsTestBuilder <TValue>(this));
        }
        /// <summary>
        /// Tests whether certain type of exception is returned from the invoked action.
        /// </summary>
        /// <typeparam name="TException">Type of the expected exception.</typeparam>
        /// <returns>The same exception test builder.</returns>
        public IAndExceptionTestBuilder OfType <TException>()
        {
            var expectedExceptionType = typeof(TException);
            var actualExceptionType   = this.CaughtException.GetType();

            if (Reflection.AreDifferentTypes(expectedExceptionType, actualExceptionType))
            {
                throw new InvalidExceptionAssertionException(string.Format(
                                                                 "When calling {0} action in {1} expected {2}, but instead received {3}.",
                                                                 this.ActionName,
                                                                 this.Controller.GetName(),
                                                                 expectedExceptionType.ToFriendlyTypeName(),
                                                                 this.CaughtException.GetName()));
            }

            return(this);
        }
        /// <inheritdoc />
        public IAndFileTestBuilder WithFileProviderOfType <TFileProvider>()
            where TFileProvider : IFileProvider
        {
            var virtualFileResult  = this.GetFileResult <VirtualFileResult>(FileProvider);
            var actualFileProvider = virtualFileResult.FileProvider;

            if (actualFileProvider == null ||
                Reflection.AreDifferentTypes(typeof(TFileProvider), actualFileProvider.GetType()))
            {
                this.ThrowNewFileResultAssertionException(
                    "FileProvider",
                    $"to be of {typeof(TFileProvider).Name} type",
                    $"instead received {actualFileProvider.GetName()}");
            }

            return(this);
        }
        /// <inheritdoc />
        public IAndViewTestBuilder WithViewEngineOfType <TViewEngine>()
            where TViewEngine : IViewEngine
        {
            var actualViewEngineType   = this.viewResult?.ViewEngine?.GetType();
            var expectedViewEngineType = typeof(TViewEngine);

            if (actualViewEngineType == null ||
                Reflection.AreDifferentTypes(expectedViewEngineType, actualViewEngineType))
            {
                throw ViewViewComponentResultAssertionException.ForViewEngineType(
                          this.TestContext.ExceptionMessagePrefix,
                          expectedViewEngineType.ToFriendlyTypeName(),
                          actualViewEngineType.ToFriendlyTypeName());
            }

            return(this);
        }
Beispiel #30
0
        /// <inheritdoc />
        public IAndMemoryCacheTestBuilder ContainingEntryOfType(object key, Type expectedType)
        {
            var value      = this.GetValue(key);
            var actualType = value.GetType();

            if (Reflection.AreDifferentTypes(expectedType, actualType))
            {
                var(expectedTypeName, actualTypeName) = (expectedType, actualType).GetTypeComparisonNames();

                this.ThrowNewDataProviderAssertionException(
                    MemoryCacheName,
                    $"to have entry with the given key and value of {expectedTypeName} type",
                    $"in fact found {actualTypeName}");
            }

            return(this);
        }