Beispiel #1
0
        public void CustomizeWithCompetingSpecimenBuilderForTheSameTypeShouldReturnTheFrozenSpecimen()
        {
            // Fixture setup
            var fixture          = new Fixture();
            var context          = new SpecimenContext(fixture);
            var frozenType       = typeof(object);
            var competingBuilder = new DelegatingSpecimenBuilder
            {
                OnCreate = (request, ctx) =>
                           request.Equals(frozenType)
                        ? new object()
#pragma warning disable 618
                        : new NoSpecimen(request)
#pragma warning restore 618
            };
            var sut = new FreezeOnMatchCustomization(
                frozenType,
                new ExactTypeSpecification(frozenType));

            // Exercise system
            fixture.Customizations.Add(competingBuilder);
            sut.Customize(fixture);
            // Verify outcome
            Assert.Equal(context.Resolve(frozenType), context.Resolve(frozenType));
        }
Beispiel #2
0
        /// <summary>
        /// Verifies that the specified property raises the PropertyChanged event.
        /// </summary>
        /// <param name="propertyInfo">The property.</param>
        /// <remarks>
        /// This method does nothing if the property does not have a public set method, or if
        /// <see cref="INotifyPropertyChanged"/> was not implemented on the properties owner.
        /// </remarks>
        /// <exception cref="ArgumentNullException"><paramref name="propertyInfo"/> is
        /// <see langword="null"/>.</exception>
        /// <exception cref="PropertyChangedRaisedException">The specified property did not raise
        /// the PropertyChanged event.</exception>
        public override void Verify(PropertyInfo propertyInfo)
        {
            ParameterValidation.IsNotNull(propertyInfo, nameof(propertyInfo));

            var propertyChangedEventInfo = propertyInfo.ReflectedType
                                           .GetInterface(nameof(INotifyPropertyChanged))
                                           ?.GetEvent(nameof(INotifyPropertyChanged.PropertyChanged));

            if (propertyChangedEventInfo != null && propertyInfo.GetSetMethod() != null)
            {
                var receivedEvents = new List <string>();
                Action <object, PropertyChangedEventArgs> handler = (sender, e) =>
                {
                    receivedEvents.Add(e.PropertyName);
                };
                var handlerDelegate = Delegate.CreateDelegate(
                    propertyChangedEventInfo.EventHandlerType,
                    handler.Target,
                    handler.Method);
                var       context              = new SpecimenContext(this.SpecimenBuilder);
                var       specimen             = context.Resolve(propertyInfo.ReflectedType);
                var       initialPropertyValue = propertyInfo.GetValue(specimen);
                var       retryCount           = 0;
                const int MaxRetryCount        = 100;
                object    newPropertyValue;
                do
                {
                    if (++retryCount > MaxRetryCount)
                    {
                        throw new PropertyChangedRaisedException(
                                  "A value unique to the initial property value could not be created.");
                    }

                    newPropertyValue = context.Resolve(propertyInfo.PropertyType);
                }while (this.propertyValueComparer.Equals(newPropertyValue, initialPropertyValue));

                try
                {
                    propertyChangedEventInfo.AddEventHandler(specimen, handlerDelegate);
                    propertyInfo.SetValue(specimen, newPropertyValue);
                }
                finally
                {
                    propertyChangedEventInfo.RemoveEventHandler(specimen, handlerDelegate);
                }

                if (receivedEvents.Count != 1 || receivedEvents[0] != propertyInfo.Name)
                {
                    throw new PropertyChangedRaisedException(propertyInfo);
                }
            }
        }
Beispiel #3
0
 private object CreateObject(Type type, SpecimenContext context)
 {
     if (type.IsArray)
     {
         var fixture = (Fixture)context.Builder;
         var objects = new object[fixture.RepeatCount];
         for (int i = 0; i < fixture.RepeatCount; i++)
         {
             objects[i] = context.Resolve(type.GetElementType());
         }
         return(objects);
     }
     return(context.Resolve(type));
 }
Beispiel #4
0
        public void CreateDoubleMixedParameterizedTypeWithNumberBasedStringGeneratorObsolete()
        {
            // Fixture setup
            var intGenerator = new Int32SequenceGenerator();
            var builder      = new CompositeSpecimenBuilder(
                intGenerator,
                new StringGenerator(() => intGenerator.CreateAnonymous()),
                new Int64SequenceGenerator(),
                new DecimalSequenceGenerator(),
                new BooleanSwitch(),
                new GuidGenerator(),
                new MethodInvoker(new ModestConstructorQuery()),
                new ParameterRequestRelay(),
                new StringSeedRelay(),
                new SeedIgnoringRelay());
            var container = new SpecimenContext(builder);
            // Exercise system
            var result = (TripleParameterType <int, string, int>)container.Resolve(typeof(TripleParameterType <int, string, int>));

            // Verify outcome
            Assert.Equal(1, result.Parameter1);
            Assert.Equal("parameter22", result.Parameter2);
            Assert.Equal(3, result.Parameter3);
            // Teardown
        }
Beispiel #5
0
        /// <summary>
        /// Returns the data to be used to test the theory.
        /// </summary>
        /// <param name="testMethod">The method that is being tested.</param>
        /// <returns>The theory data generated by <see cref="Fixture"/>.</returns>
        public override IEnumerable <object[]> GetData(MethodInfo testMethod)
        {
            if (testMethod == null)
            {
                throw new ArgumentNullException(nameof(testMethod));
            }

            if (testMethod.DeclaringType != null)
            {
                LoadingAssemblies.Add(testMethod.DeclaringType.Assembly);
            }

            var fixture = AutoFixture.AutoFixtureFactory.GetInstance(LoadingAssemblies);

            var specimens = new List <object>();

            foreach (var p in testMethod.GetParameters())
            {
                var context  = new SpecimenContext(fixture);
                var specimen = context.Resolve(p);
                specimens.Add(specimen);
            }

            return(new[] { specimens.ToArray() });
        }
        public void IsDefaultValue_should_return_false_when_value_is_valid(Type type)
        {
            var context = new SpecimenContext(fixture);
            var value   = context.Resolve(type);

            Assert.That(Extensions.IsDefaultValue(value), Is.False);
        }
        private ISpecimenBuilder FreezeSpecimen(IFixture fixture)
        {
            var context  = new SpecimenContext(fixture);
            var specimen = context.Resolve(this.Request);

            return(new FixedBuilder(specimen));
        }
        private ISpecimenBuilder FreezeTargetType(IFixture fixture)
        {
            var context  = new SpecimenContext(fixture);
            var specimen = context.Resolve(this.targetType);

            return(new FixedBuilder(specimen));
        }
Beispiel #9
0
        public void CombineExplicitPropertyWithAutoProperties()
        {
            // Arrange
            var expectedText = "Fnaah";

            var specifiedCommand = new BindingCommand <DoublePropertyHolder <string, int>, string>(ph => ph.Property1, expectedText);
            var reservedProperty = new InverseRequestSpecification(specifiedCommand);

            var customizedBuilder = new Postprocessor(
                new Postprocessor(
                    new MethodInvoker(new ModestConstructorQuery()),
                    specifiedCommand),
                new AutoPropertiesCommand(reservedProperty),
                new AnyTypeSpecification());

            var builder = new CompositeSpecimenBuilder(
                customizedBuilder,
                Scenario.CreateAutoPropertyBuilder());
            var container = new SpecimenContext(builder);
            // Act
            var result = container.Resolve(typeof(DoublePropertyHolder <string, int>));
            // Assert
            var actual = Assert.IsAssignableFrom <DoublePropertyHolder <string, int> >(result);

            Assert.Equal(expectedText, actual.Property1);
            Assert.Equal(1, actual.Property2);
        }
        private object Resolve(ParameterInfo p)
        {
#pragma warning disable 618
            var context = new SpecimenContext(this.Fixture);
#pragma warning restore 618
            return(context.Resolve(p));
        }
        private static TestOperation[] TestOperations()
        {
            var fixture    = new Fixture();
            var context    = new SpecimenContext(fixture);
            var allOpTypes = AllOperations.GetAllTypes();

            return(allOpTypes.Select(type => (TestOperation)context.Resolve(type)).ToArray());
        }
        /// <inerhitdoc />
        public object GenerateAnonymousValue(AnonymousValueFixture any, Type type, string propertyName)
        {
            // http://autofixture.codeplex.com/workitem/4229
            var context  = new SpecimenContext(any.Fixture);
            var specimen = context.Resolve(type);

            return(specimen);
        }
Beispiel #13
0
        public static object CustomizeAndCreate(ParameterInfo p, IFixture fixture)
        {
            var customizations = p.GetCustomAttributes(typeof(CustomizeAttribute), false)
                                 .OfType <CustomizeAttribute>()
                                 .Select(attr => attr.GetCustomization(p));

            var context = new SpecimenContext(ApplyCustomizations(fixture, customizations));

            return(context.Resolve(p));
        }
        public void FreezeByMatchingImplementedInterfacesShouldReturnTheRightSpecimen(
            Type frozenType,
            Type requestedType)
        {
            // Arrange
            var fixture = new Fixture();
            var context = new SpecimenContext(fixture);
            var sut     = new FreezeOnMatchCustomization(
                frozenType,
                new ImplementedInterfaceSpecification(frozenType));

            // Act
            sut.Customize(fixture);
            // Assert
            var frozen    = context.Resolve(frozenType);
            var requested = context.Resolve(requestedType);

            Assert.Same(frozen, requested);
        }
        private static IndexedReplacement <object> RecreateExpansion(
            ISpecimenBuilder specimenBuilder,
            IMethod method,
            IndexedReplacement <object> oldExpansion)
        {
            var context = new SpecimenContext(specimenBuilder);

            return(new IndexedReplacement <object>(
                       oldExpansion.ReplacementIndex,
                       method.Parameters.Select(p => context.Resolve(p))));
        }
        public void FreezeByMatchingBaseTypeShouldReturnTheRightSpecimen(
            Type frozenType,
            Type requestedType,
            bool areEqual)
        {
            // Arrange
            var fixture = new Fixture();
            var context = new SpecimenContext(fixture);
            var sut     = new FreezeOnMatchCustomization(
                frozenType,
                new DirectBaseTypeSpecification(frozenType));

            // Act
            sut.Customize(fixture);
            // Assert
            var frozen    = context.Resolve(frozenType);
            var requested = context.Resolve(requestedType);

            Assert.Equal(areEqual, frozen.Equals(requested));
        }
Beispiel #17
0
        public void FixtureDoesNotHijackCollectionInterfacesIfAnotherCustomizationExistsForThem(Type collectionInterface)
        {
            // Fixture setup
            var fixture = new Fixture().Customize(new MultipleCustomization()).Customize(new AutoNSubstituteCustomization());
            var context = new SpecimenContext(fixture);
            // Exercise system
            var result = context.Resolve(new SeededRequest(collectionInterface, null));

            // Verify outcome
            Assert.NotEmpty((IEnumerable)result);
        }
Beispiel #18
0
        public void FreezeByMatchingImplementedInterfacesShouldReturnTheRightSpecimen(
            Type frozenType,
            Type requestedType)
        {
            // Fixture setup
            var fixture = new Fixture();
            var context = new SpecimenContext(fixture);
            var sut     = new FreezeOnMatchCustomization(
                frozenType,
                new ImplementedInterfaceSpecification(frozenType));

            // Exercise system
            sut.Customize(fixture);
            // Verify outcome
            var frozen    = context.Resolve(frozenType);
            var requested = context.Resolve(requestedType);

            Assert.Same(frozen, requested);
            // Teardown
        }
Beispiel #19
0
        public static IReturnsResult <TMock> ReturnsAsyncUsingFixture <TMock, TResult>(this IReturns <TMock, Task <TResult> > setup, ISpecimenBuilder fixture)
            where TMock : class
        {
            var context = new SpecimenContext(fixture);

            return(setup.ReturnsAsync(() =>
            {
                var obj = context.Resolve(typeof(TResult));
                return (TResult)obj;
            }));
        }
Beispiel #20
0
        public void FixtureDoesNotHijackCollectionInterfaces(Type collectionInterface)
        {
            // Arrange
            var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
            var context = new SpecimenContext(fixture);
            // Act
            var result = context.Resolve(new SeededRequest(collectionInterface, null));

            // Assert
            Assert.NotEmpty((IEnumerable)result);
        }
        public static TParameter FreezeParameter <TType, TParameter>(this IFixture fixture)
        {
            var context  = new SpecimenContext(fixture);
            var specimen = context.Resolve(typeof(TParameter));

            fixture.Customize(
                new FreezeSpecimenOnMatchCustomization(
                    specimen,
                    new DeclaringTypeParameterSpecification(typeof(TType), typeof(TParameter))));

            return((TParameter)specimen);
        }
Beispiel #22
0
        public void CustomizeWithEqualRequestsShouldFreezeSpecimen()
        {
            // Fixture setup
            var fixture = new Fixture();
            var context = new SpecimenContext(fixture);

            var freezingRequest = typeof(ConcreteType).GetProperty(
                nameof(ConcreteType.Property1));
            var equalRequest = typeof(ConcreteType).GetProperty(
                nameof(ConcreteType.Property1));

            var sut = new FreezeOnMatchCustomization(freezingRequest);

            // Exercise system
            sut.Customize(fixture);
            // Verify outcome
            var frozen    = context.Resolve(freezingRequest);
            var requested = context.Resolve(equalRequest);

            Assert.True(frozen.Equals(requested));
        }
Beispiel #23
0
        public void FreezeByMatchingBaseTypeShouldReturnTheRightSpecimen(
            Type frozenType,
            Type requestedType,
            bool areEqual)
        {
            // Fixture setup
            var fixture = new Fixture();
            var context = new SpecimenContext(fixture);
            var sut     = new FreezeOnMatchCustomization(
                frozenType,
                new DirectBaseTypeSpecification(frozenType));

            // Exercise system
            sut.Customize(fixture);
            // Verify outcome
            var frozen    = context.Resolve(frozenType);
            var requested = context.Resolve(requestedType);

            Assert.Equal(areEqual, frozen.Equals(requested));
            // Teardown
        }
        public void CustomizeWithNotEqualRequestsShouldNotFreezeSpecimen()
        {
            // Arrange
            var fixture = new Fixture();
            var context = new SpecimenContext(fixture);

            var freezingRequest = typeof(ConcreteType).GetProperty(
                nameof(ConcreteType.Property1));
            var anotherRequest = typeof(ConcreteType).GetProperty(
                nameof(ConcreteType.Property2));

            var sut = new FreezeOnMatchCustomization(freezingRequest);

            // Act
            sut.Customize(fixture);
            // Assert
            var frozen    = context.Resolve(freezingRequest);
            var requested = context.Resolve(anotherRequest);

            Assert.False(frozen.Equals(requested));
        }
        private static object[] CreateCtorArgs(IFixture fixture, Type[] ctorArgumentTypes)
        {
            if (ctorArgumentTypes.Length == 0)
            {
                return(new object[0]);
            }

            var context = new SpecimenContext(fixture);

            return(ctorArgumentTypes
                   .Select(t => t.IsInterface ? CreateMockForType(t) : context.Resolve(t))
                   .ToArray());
        }
    private object CustomizeAndCreate(IFixture fixture, ParameterInfo p)
    {
        var customizations = p.GetCustomAttributes(typeof(CustomizeAttribute), false)
                             .OfType <CustomizeAttribute>()
                             .Select(attr => attr.GetCustomization(p));

        foreach (var c in customizations)
        {
            fixture.Customize(c);
        }
        var context = new SpecimenContext(fixture);

        return(context.Resolve(p));
    }
 private TestCaseParameters GetParametersForMethod(IMethodInfo method)
 {
     try
     {
         var specimenBuilder = new SpecimenContext(this._fixture);
         var parameterValues = method.GetParameters()
                               .Select(p => specimenBuilder.Resolve(p.ParameterInfo))
                               .ToArray();
         return(new TestCaseParameters(parameterValues));
     }
     catch (Exception ex)
     {
         return(new TestCaseParameters(ex));
     }
 }
        public IEnumerable <object[]> GetData(MethodInfo methodInfo)
        {
            IFixture generator = CreateGenerator();

            var arguments = new List <object>();

            foreach (ParameterInfo parameter in methodInfo.GetParameters())
            {
                var    context  = new SpecimenContext(generator);
                object argument = context.Resolve(parameter);
                arguments.Add(argument);
            }

            yield return(arguments.ToArray());
        }
        public override bool TryGetMember(
            GetMemberBinder binder,
            out object result)
        {
            if (binder.Name == "Bar")
            {
                result = context.Resolve(typeof(string));
            }
            else
            {
                result = new AnythingObject(context.Builder);
            }

            return(true);
        }
        public void CustomizeWithCompetingSpecimenBuilderForTheSameRequestShouldReturnTheFrozenSpecimen()
        {
            // Arrange
            var fixture          = new Fixture();
            var context          = new SpecimenContext(fixture);
            var request          = new object();
            var requestType      = typeof(object);
            var competingBuilder = new DelegatingSpecimenBuilder
            {
                OnCreate = (req, ctx) =>
                           req.Equals(request)
                        ? new object()
                        : new NoSpecimen()
            };
            var sut = new FreezeOnMatchCustomization(
                request,
                new ExactTypeSpecification(requestType));

            // Act
            fixture.Customizations.Add(competingBuilder);
            sut.Customize(fixture);
            // Assert
            Assert.Equal(context.Resolve(requestType), context.Resolve(requestType));
        }