Exemplo n.º 1
0
        public void BuildWithAssignmentsSkipsAssignmentsWithOneAssignment()
        {
            var assignments     = new[] { new AssignmentInfoCollection() };
            var memberField     = new CodeMemberField(typeof(int), "myField");
            var assignStatement = new CodeAssignStatement();
            var ctorAssignment  = new ConstructorAssignment("theParameter", assignStatement, memberField, typeof(string));

            assignments[0].AddAssignment(ctorAssignment);
            //assignments[0].UsedConstructor =

            var tobuilder = this.mocks.StrictMock <ITestObjectComposer>();

            Expect.Call(tobuilder.Assignments).Return(assignments);

            var stcontext = this.mocks.StrictMock <ISetupAndTearDownCreationContext>();

            Expect.Call(stcontext.TestObjectCreator).Return(tobuilder);

            Expect.Call(this.context.SetUpTearDownContext).Return(stcontext);//.Repeat.Any();
            mocks.ReplayAll();
            var expected = true;
            var actual   = testObject.Build(this.context);

            Assert.AreEqual(expected, actual);

            mocks.VerifyAll();
        }
Exemplo n.º 2
0
        public void PropertyItemIndexNormalBehavior()
        {
            // Test read access of 'Indexer' Property.
            var expected = new ConstructorAssignment("ParameterName", new CodeAssignStatement(), new CodeMemberField(), typeof(string));

            testObject.AddAssignment(expected);
            var actual = testObject["ParameterName"];

            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 3
0
        public void PropertyItemIndexWithNotPresentKey()
        {
            // Test read access of 'Indexer' Property with a key that is not present.
            var actual = testObject["NotPresent"];

            Assert.IsNull(actual);

            var item = new ConstructorAssignment("ParameterName", new CodeAssignStatement(), new CodeMemberField(), typeof(string));

            testObject.AddAssignment(item);
            actual = testObject["AnotherNotPresent"];
            Assert.IsNull(actual);
        }
Exemplo n.º 4
0
        public void AddAssignmentWithSameKeyShouldThrow()
        {
            var item = new ConstructorAssignment("ParameterName", new CodeAssignStatement(), new CodeMemberField(), typeof(string));

            testObject.AddAssignment(item);
            Assert.AreEqual(1, testObject.Count);

            Assert.Throws <ArgumentException>(() => testObject.AddAssignment(item));
            Assert.AreEqual(1, testObject.Count);

            var item2 = new ConstructorAssignment("ParameterName", new CodeAssignStatement(), new CodeMemberField(), typeof(string));

            Assert.Throws <ArgumentException>(() => testObject.AddAssignment(item2));
            Assert.AreEqual(1, testObject.Count);
        }
Exemplo n.º 5
0
        private void CreateMocker(
            CodeTypeDeclaration testClassDeclaration,
            CodeMemberMethod setUpMethod,
            CodeMemberField mockRepositoryMemberField,
            List <CodeAssignStatement> mockAssignments,
            Type paraType,
            string paraName,
            ConstructorAssignment data)
        {
            if (data != null && data.MemberFieldName != data.ParameterName)
            {
            }
            // reuse already present field assignments.
            var mockMemberField = testClassDeclaration
                                  .Members.OfType <CodeMemberField>()
                                  .Where(e => e.Name == paraName)
                                  .FirstOrDefault();
            var mockMemberFieldCreated = false;

            if (mockMemberField == null)
            {
                mockMemberField = AddTestMemberField(
                    testClassDeclaration, paraType.FullName, paraName);
                mockMemberFieldCreated = true;
            }

            var mockAssignment = this.AddMockObject(mockRepositoryMemberField, paraType.FullName, paraName);

            if (mockMemberFieldCreated)
            {
                // none found, add a new assignment.
                setUpMethod.Statements.Add(mockAssignment);
            }
            else
            {
                if (data != null)
                {
                    data.AssignStatement.Right = mockAssignment.Right;
                }
            }

            mockAssignments.Add(mockAssignment);
        }
Exemplo n.º 6
0
        public void AddAssignmentTest()
        {
            var expected = new ConstructorAssignment("ParameterName", new CodeAssignStatement(), new CodeMemberField(), typeof(string));

            testObject.AddAssignment(expected);
            Assert.AreEqual(1, testObject.Count);
            var actual = testObject["ParameterName"];

            Assert.AreEqual(expected, actual);

            var expected2 = new ConstructorAssignment("OtherParameterName", new CodeAssignStatement(), new CodeMemberField(), typeof(string));

            testObject.AddAssignment(expected2);
            actual = testObject["OtherParameterName"];
            Assert.AreEqual(2, testObject.Count);
            Assert.AreEqual(expected2, actual);
            actual = testObject["ParameterName"];
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 7
0
        /*/// <summary>
         * /// Compose additional items of the test setup method.
         * /// </summary>
         * /// <param name="setUpMethod">The test setup method.</param>
         * /// <param name="testObjectMemberField">The member field of the object under test.</param>
         * /// <param name="testObjectName">The name of the object under test.</param>
         * /// <returns>
         * /// The initialization expression of the object under test.
         * /// Is <c>null</c>, when none is created.
         * /// </returns>
         * protected override CodeObjectCreateExpression ComposeTestSetupMethod(
         *  CodeMemberMethod setUpMethod,
         *  CodeMemberField testObjectMemberField,
         *  string testObjectName)
         * {
         *  //var invokeExpression = new CodeMethodInvokeExpression(
         *    //  new CodeTypeReferenceExpression("Assert"),
         *    //  "AreEqual",
         *      //new CodePrimitiveExpression("expected")
         *   //   new CodeFieldReferenceExpression(testObjectMemberField, "bla")
         *   //   , new CodeVariableReferenceExpression("actual"));
         *  var fieldRef1 =
         *      new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), testObjectMemberField.Name);
         *
         *  var testObjectMemberFieldCreate = new CodeObjectCreateExpression(testObjectName, new CodeExpression[] { });
         *  var as1 = new CodeAssignStatement(fieldRef1, testObjectMemberFieldCreate);
         *
         *  // Creates a statement using a code expression.
         *  // var expressionStatement = new CodeExpressionStatement(fieldRef1);
         *  setUpMethod.Statements.Add(as1);
         *  return testObjectMemberFieldCreate;
         * }*/

        /// <summary>
        /// Compose additional items of the test setup method.
        /// </summary>
        /// <param name="context">The setup context.</param>
        /// <param name="testObjectMemberField">The member field of the object under test.</param>
        /// <param name="testObjectName">The name of the object under test.</param>
        /// <returns>
        /// The list of assigned mock objects.
        /// </returns>
        protected virtual IEnumerable <CodeAssignStatement> ComposeTestSetupMockery(
            ISetupAndTearDownCreationContext context,
            CodeMemberField testObjectMemberField,
            string testObjectName)
        {
            CodeTypeDeclaration testClassDeclaration = context.TestClassDeclaration;
            CodeMemberMethod    setUpMethod          = context.SetUpMethod;

            // Todo: only the Type is necs, the CodeTypeDeclaration is too much knowledge.
            var testObjectClassType = (Type)testClassDeclaration.UserData[NStubConstants.UserDataClassTypeKey];

            Type[] parameters = { /*typeof(int)*/ };

            // Get the constructor that takes an integer as a parameter.
            var flags     = BindingFlags.Instance;
            var noPrivate = true;

            switch (Configuration.MethodGeneratorLevelOfDetail)
            {
            case MemberVisibility.Public:
                flags |= BindingFlags.Public;
                break;

            case MemberVisibility.Internal:
                flags |= BindingFlags.Public | BindingFlags.NonPublic;
                break;

            case MemberVisibility.Private:
                flags    |= BindingFlags.Public | BindingFlags.NonPublic;
                noPrivate = false;
                break;

            default:
                break;
            }

            var ctor = testObjectClassType.GetConstructor(flags, Type.DefaultBinder, parameters, null);

            if (ctor == null)
            {
                // outputBlock.Text +=
                // "There is no public constructor of MyClass that takes an integer as a parameter.\n";
            }

            // else
            // {
            // outputBlock.Text +=
            // "The public constructor of MyClass that takes an integer as a parameter is:\n";
            // outputBlock.Text += ctor.ToString() + "\n";
            // }
            var  testObjectConstructors       = testObjectClassType.GetConstructors(flags);
            bool hasInterfaceInCtorParameters = false;
            var  ctorParameterTypes           = new List <ParameterInfo>();

            foreach (var constructor in testObjectConstructors)
            {
                if (noPrivate && constructor.IsPrivate)
                {
                    continue;
                }

                var ctorParameters = constructor.GetParameters();
                foreach (var para in ctorParameters)
                {
                    if (para.ParameterType.IsInterface /*&& !para.ParameterType.IsGenericType*/)
                    {
                        hasInterfaceInCtorParameters = true;
                        ctorParameterTypes.Add(para);
                    }
                }
            }

            if (!hasInterfaceInCtorParameters)
            {
                return(new CodeAssignStatement[0]);
            }

            var testObjectInitializerPosition = setUpMethod.Statements.Count - 1;

            var mockRepositoryMemberField = this.AddMockRepository(
                testClassDeclaration, setUpMethod, "mocks");

            var mockAssignments = new List <CodeAssignStatement>();

            foreach (var paraInfo in ctorParameterTypes)
            {
                IBuilderData          data;
                ConstructorAssignment ctorassignment = null;

                if (paraInfo.ParameterType.IsGenericType)
                {
                    var genericTypeDefinition = paraInfo.ParameterType.GetGenericTypeDefinition();
                    if (typeof(IEnumerable <>).IsAssignableFrom(genericTypeDefinition))
                    {
                        // try to find the testobjcomposer assigned sub items for IEnumerable<T>'s.
                        BuildProperties.TryGetValue(
                            "CreateAssignments." + testObjectClassType.FullName + "." + paraInfo.Name,
                            paraInfo.Name + "Item",
                            out data);
                        if (data != null)
                        {
                            ctorassignment = data.GetData() as ConstructorAssignment;
                        }

                        if (testObjectClassType.Name == "DefaultMemberBuilderFactory")
                        {
                        }

                        if (ctorassignment != null)
                        {
                            this.CreateMocker(
                                testClassDeclaration,
                                setUpMethod,
                                mockRepositoryMemberField,
                                mockAssignments,
                                ctorassignment.MemberType,
                                paraInfo.Name,
                                ctorassignment);
                        }

                        continue;
                    }
                }

                BuildProperties.TryGetValue(
                    "Assignments." + testObjectClassType.FullName,
                    paraInfo.Name,
                    out data);
                if (data != null)
                {
                    ctorassignment = data.GetData() as ConstructorAssignment;
                }

                this.CreateMocker(
                    testClassDeclaration,
                    setUpMethod,
                    mockRepositoryMemberField,
                    mockAssignments,
                    paraInfo.ParameterType,
                    paraInfo.Name,
                    ctorassignment);
            }

            // reorder the testObject initializer to the bottom of the SetUp method.
            // var removedTypedec = setUpMethod.Statements[testObjectInitializerPosition];
            // setUpMethod.Statements.RemoveAt(testObjectInitializerPosition);
            // setUpMethod.Statements.Add(removedTypedec);
            return(mockAssignments);
        }
Exemplo n.º 8
0
        public void BuildWithAssignmentsNoMatchingParameters()
        {
            var method          = new CodeMemberMethod();
            var assCol1         = new AssignmentInfoCollection();
            var assCol2         = new AssignmentInfoCollection();
            var assignments     = new[] { assCol1, assCol2 };
            var memberField     = new CodeMemberField(typeof(int), "myField");
            var assignStatement = new CodeAssignStatement();
            var ctorAssignment  = new ConstructorAssignment("theParameter", assignStatement, memberField, typeof(string));

            assignments[0].AddAssignment(ctorAssignment);
            var helpctors = typeof(ConstructorBuilderHelpType).GetConstructors();

            assignments[0].UsedConstructor = helpctors[0];
            assignments[1].UsedConstructor = helpctors[0];

            var tobuilder = this.mocks.StrictMock <ITestObjectComposer>();

            Expect.Call(tobuilder.Assignments).Return(assignments);

            var stcontext = this.mocks.StrictMock <ISetupAndTearDownCreationContext>();

            Expect.Call(stcontext.TestObjectCreator).Return(tobuilder);

            Expect.Call(this.context.SetUpTearDownContext).Return(stcontext);//.Repeat.Any();
            Expect.Call(this.context.TestObjectType).Return(typeof(int)).Repeat.AtLeastOnce();
            var ctdecl = new CodeTypeDeclaration("TheTestClass");

            Expect.Call(this.context.TestClassDeclaration).Return(ctdecl).Repeat.AtLeastOnce();
            var buildResult = new MemberBuildResult();

            Expect.Call(this.context.BuildResult).Return(buildResult).Repeat.AtLeastOnce();

            Expect.Call(delegate { tobuilder.AssignExtra(ctdecl, method, null, assCol1); })
            //.Constraints(Is.Equal(ctdecl), Is.Equal(method), Is.Anything(), Is.Equal(assCol1)
            .Constraints(Is.Equal(ctdecl), Is.Anything(), Is.Anything(), Is.Equal(assCol1))
            .Do((Action <CodeTypeDeclaration, CodeMemberMethod, CodeObjectCreateExpression, AssignmentInfoCollection>)
                delegate(CodeTypeDeclaration testClassDeclaration,
                         CodeMemberMethod testMethod,
                         CodeObjectCreateExpression testObjectConstructor,
                         AssignmentInfoCollection ctorAssignments)
            {
                var a = testClassDeclaration;
                var b = testMethod;
                Assert.IsInstanceOfType <CustomConstructorCodeMemberMethod>(testMethod);
                Assert.AreEqual("ConstructWithParametersTheIntParameterTest", testMethod.Name);
                var c = testObjectConstructor;
                Assert.IsEmpty(testObjectConstructor.Parameters);
                Assert.AreEqual("Int32", testObjectConstructor.CreateType.BaseType);
                var d = ctorAssignment;

                var e = ctorAssignment;
            });
            Expect.Call(delegate { tobuilder.AssignExtra(ctdecl, method, null, assCol1); })
            //.Constraints(Is.Equal(ctdecl), Is.Equal(method), Is.Anything(), Is.Equal(assCol1)
            .Constraints(Is.Equal(ctdecl), Is.Anything(), Is.Anything(), Is.Equal(assCol2)
                         );
            mocks.ReplayAll();
            var expected = true;
            var actual   = testObject.Build(this.context);

            Assert.AreEqual(expected, actual);

            // there should be two methods (constructor testers) added.
            Assert.Count(2, buildResult.ClassMethodsToAdd);
            var bresList = buildResult.ClassMethodsToAdd.ToList();

            Assert.IsInstanceOfType <CustomConstructorCodeMemberMethod>(bresList[0]);
            Assert.IsInstanceOfType <CustomConstructorCodeMemberMethod>(bresList[1]);

            mocks.VerifyAll();
        }
Exemplo n.º 9
0
        public void BuildWithAssignmentsSkipsAssignmentsWithOneAssignment()
        {
            var assignments = new[] { new AssignmentInfoCollection()};
            var memberField = new CodeMemberField(typeof(int), "myField");
            var assignStatement = new CodeAssignStatement();
            var ctorAssignment = new ConstructorAssignment("theParameter", assignStatement, memberField, typeof(string));
            assignments[0].AddAssignment(ctorAssignment);
            //assignments[0].UsedConstructor =

            var tobuilder = this.mocks.StrictMock<ITestObjectComposer>();
            Expect.Call(tobuilder.Assignments).Return(assignments);

            var stcontext = this.mocks.StrictMock<ISetupAndTearDownCreationContext>();
            Expect.Call(stcontext.TestObjectCreator).Return(tobuilder);

            Expect.Call(this.context.SetUpTearDownContext).Return(stcontext);//.Repeat.Any();
            mocks.ReplayAll();
            var expected = true;
            var actual = testObject.Build(this.context);
            Assert.AreEqual(expected, actual);

            mocks.VerifyAll();
        }
Exemplo n.º 10
0
        public void BuildWithAssignmentsNoMatchingParameters()
        {
            var method = new CodeMemberMethod();
            var assCol1 = new AssignmentInfoCollection();
            var assCol2 = new AssignmentInfoCollection();
            var assignments = new[] { assCol1, assCol2 };
            var memberField = new CodeMemberField(typeof(int), "myField");
            var assignStatement = new CodeAssignStatement();
            var ctorAssignment = new ConstructorAssignment("theParameter", assignStatement, memberField, typeof(string));
            assignments[0].AddAssignment(ctorAssignment);
            var helpctors = typeof(ConstructorBuilderHelpType).GetConstructors();
            assignments[0].UsedConstructor = helpctors[0];
            assignments[1].UsedConstructor = helpctors[0];

            var tobuilder = this.mocks.StrictMock<ITestObjectComposer>();
            Expect.Call(tobuilder.Assignments).Return(assignments);

            var stcontext = this.mocks.StrictMock<ISetupAndTearDownCreationContext>();
            Expect.Call(stcontext.TestObjectCreator).Return(tobuilder);

            Expect.Call(this.context.SetUpTearDownContext).Return(stcontext);//.Repeat.Any();
            Expect.Call(this.context.TestObjectType).Return(typeof(int)).Repeat.AtLeastOnce();
            var ctdecl = new CodeTypeDeclaration("TheTestClass");
            Expect.Call(this.context.TestClassDeclaration).Return(ctdecl).Repeat.AtLeastOnce();
            var buildResult = new MemberBuildResult();
            Expect.Call(this.context.BuildResult).Return(buildResult).Repeat.AtLeastOnce();

            Expect.Call(delegate { tobuilder.AssignExtra(ctdecl, method, null, assCol1); })
                //.Constraints(Is.Equal(ctdecl), Is.Equal(method), Is.Anything(), Is.Equal(assCol1)
                .Constraints(Is.Equal(ctdecl), Is.Anything(), Is.Anything(), Is.Equal(assCol1))
                .Do((Action<CodeTypeDeclaration,CodeMemberMethod,CodeObjectCreateExpression ,AssignmentInfoCollection>)
                delegate(CodeTypeDeclaration testClassDeclaration,
            CodeMemberMethod testMethod,
            CodeObjectCreateExpression testObjectConstructor,
            AssignmentInfoCollection ctorAssignments)
            {
                var a = testClassDeclaration;
                var b = testMethod;
                Assert.IsInstanceOfType<CustomConstructorCodeMemberMethod>(testMethod);
                Assert.AreEqual("ConstructWithParametersTheIntParameterTest", testMethod.Name);
                var c = testObjectConstructor;
                Assert.IsEmpty(testObjectConstructor.Parameters);
                Assert.AreEqual("Int32", testObjectConstructor.CreateType.BaseType);
                var d = ctorAssignment;

                var e = ctorAssignment;
            });
            Expect.Call(delegate { tobuilder.AssignExtra(ctdecl, method, null, assCol1); })
                //.Constraints(Is.Equal(ctdecl), Is.Equal(method), Is.Anything(), Is.Equal(assCol1)
                .Constraints(Is.Equal(ctdecl), Is.Anything(), Is.Anything(), Is.Equal(assCol2)
                );
            mocks.ReplayAll();
            var expected = true;
            var actual = testObject.Build(this.context);
            Assert.AreEqual(expected, actual);

            // there should be two methods (constructor testers) added.
            Assert.Count(2, buildResult.ClassMethodsToAdd);
            var bresList = buildResult.ClassMethodsToAdd.ToList();
            Assert.IsInstanceOfType<CustomConstructorCodeMemberMethod>(bresList[0]);
            Assert.IsInstanceOfType<CustomConstructorCodeMemberMethod>(bresList[1]);

            mocks.VerifyAll();
        }