Beispiel #1
0
        private static void WriteUsings(StringBuilder builder, TestGenerationContext context)
        {
            List <string> namespaces = new List <string>();

            namespaces.AddRange(context.MockFramework.UsingNamespaces);
            namespaces.Add(context.TestFramework.UsingNamespace);
            namespaces.Add(context.ClassNamespace);

            if (context.TestFramework.TestCleanupStyle == TestCleanupStyle.Disposable)
            {
                namespaces.Add("System");
            }

            foreach (InjectableType injectedType in context.InjectedTypes)
            {
                namespaces.AddRange(injectedType.TypeNamespaces);
            }

            namespaces = namespaces.Distinct().ToList();
            namespaces.Sort(StringComparer.Ordinal);

            for (int i = 0; i < namespaces.Count; i++)
            {
                builder.Append($"using {namespaces[i]};");

                if (i < namespaces.Count - 1)
                {
                    builder.AppendLine();
                }
            }
        }
        private static void WriteParameterSetupDefaults(StringBuilder builder, TestGenerationContext context, MethodDescriptor methodDescriptor)
        {
            int numberOfParameters = methodDescriptor.MethodParameters.Count();

            for (int j = 0; j < numberOfParameters; j++)
            {
                TypeDescriptor typeInformation = methodDescriptor.MethodParameters[j].TypeInformation;

                string argumentValue;
                if (typeInformation.TypeSymbol != null)
                {
                    // If we have proper type information, generate the default expression for this type
                    var generator = Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(context.Document);
                    argumentValue = generator.DefaultExpression(typeInformation.TypeSymbol).ToString();
                }
                else
                {
                    argumentValue = "TODO";
                }

                builder.Append($"{typeInformation} {methodDescriptor.MethodParameters[j].ArgumentName} = {argumentValue};");
                if (j < numberOfParameters - 1)
                {
                    builder.AppendLine();
                }
            }
        }
        private void WriteTestMethodName(StringBuilder builder, TestGenerationContext context, MethodDescriptor methodDescriptor)
        {
            string testMethodNameTemplate = this.Settings.GetTemplate(
                context.TestFramework,
                context.MockFramework,
                TemplateType.TestMethodName);

            string baseTestMethodName = StringUtilities.ReplaceTokens(
                testMethodNameTemplate,
                (tokenName2, propertyIndex2, builder2) =>
            {
                if (WriteGlobalToken(tokenName2, builder2, context))
                {
                    return;
                }

                if (WriteTestMethodNameToken(tokenName2, builder2, methodDescriptor))
                {
                    return;
                }

                WriteTokenPassthrough(tokenName2, builder2);
            });

            var testMethodName = CreateUniqueTestMethodName(context, baseTestMethodName);

            context.UsedTestMethodNames.Add(testMethodName);
            builder.Append(testMethodName);
        }
Beispiel #4
0
        private void WriteMockFieldInitializations(StringBuilder builder, TestGenerationContext context)
        {
            string template = context.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.MockFieldInitialization);
            IDictionary <string, string> customMocks = context.Settings.CustomMocks;

            for (int i = 0; i < context.InjectedTypes.Count; i++)
            {
                InjectableType injectedType = context.InjectedTypes[i];
                string         line;
                if (customMocks.TryGetValue(injectedType.FullName, out string customMockClassFull))
                {
                    string customMockClassName = StringUtilities.GetShortNameFromFullTypeName(customMockClassFull);
                    line = ReplaceInterfaceTokensCustom(context.Settings.CustomMockFieldInitializationTemplate, injectedType, context, customMockClassName);
                }
                else
                {
                    line = ReplaceInterfaceTokens(template, injectedType, context);
                }

                builder.Append(line);

                if (i < context.InjectedTypes.Count - 1)
                {
                    builder.AppendLine();
                }
            }
        }
        private void WriteTestMethods(StringBuilder builder, TestGenerationContext context)
        {
            if (context.MethodDeclarations.Count == 0)
            {
                string testMethodEmptyTemplate = this.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.TestMethodEmpty);
                WriteTestMethod(builder, context, testMethodEmptyTemplate);

                return;
            }

            string testMethodInvokeTemplate = this.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.TestMethodInvocation);

            for (int i = 0; i < context.MethodDeclarations.Count; i++)
            {
                var methodDescriptor = context.MethodDeclarations[i];

                WriteTestMethod(builder, context, testMethodInvokeTemplate, methodDescriptor);

                // Write separator line
                if (i < context.MethodDeclarations.Count - 1)
                {
                    builder.AppendLine();                     // Finish the line with the closing }
                    builder.AppendLine();                     // Make a blank line
                }
            }
        }
        private void WriteTestMethod(StringBuilder builder, TestGenerationContext context, string testTemplate, MethodDescriptor methodDescriptor = null)
        {
            string filledTemplate = StringUtilities.ReplaceTokens(
                testTemplate,
                (tokenName, propertyIndex, builder2) =>
            {
                if (WriteGlobalToken(tokenName, builder2, context))
                {
                    return;
                }

                if (this.WriteTestMethodCommonToken(tokenName, propertyIndex, builder2, context, testTemplate))
                {
                    return;
                }

                if (methodDescriptor != null && this.WriteTestMethodInvocationToken(tokenName, propertyIndex, builder2, context, testTemplate, methodDescriptor))
                {
                    return;
                }

                WriteTokenPassthrough(tokenName, builder2);
            });

            builder.Append(filledTemplate);
        }
        private string GenerateUnitTestContents(TestGenerationContext context)
        {
            TestFramework testFramework = context.TestFramework;
            MockFramework mockFramework = context.MockFramework;

            string fileTemplate   = this.Settings.GetTemplate(testFramework, mockFramework, TemplateType.File);
            string filledTemplate = StringUtilities.ReplaceTokens(
                fileTemplate,
                (tokenName, propertyIndex, builder) =>
            {
                if (WriteGlobalToken(tokenName, builder, context))
                {
                    return;
                }

                if (WriteContentToken(tokenName, propertyIndex, builder, context, fileTemplate))
                {
                    return;
                }

                WriteTokenPassthrough(tokenName, builder);
            });

            SyntaxTree tree          = CSharpSyntaxTree.ParseText(filledTemplate);
            SyntaxNode formattedNode = Formatter.Format(tree.GetRoot(), CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace);

            return(formattedNode.ToFullString());
        }
        public async Task GenerateUnitTestFileAsync(
            ProjectItemSummary selectedFile,
            string targetFilePath,
            string targetProjectNamespace,
            TestFramework testFramework,
            MockFramework mockFramework)
        {
            string sourceProjectDirectory = Path.GetDirectoryName(selectedFile.ProjectFilePath);
            string selectedFileDirectory  = Path.GetDirectoryName(selectedFile.FilePath);

            if (sourceProjectDirectory == null || selectedFileDirectory == null || !selectedFileDirectory.StartsWith(sourceProjectDirectory, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Error with selected file paths.");
            }

            TestGenerationContext context = await this.CollectTestGenerationContextAsync(selectedFile, targetProjectNamespace, testFramework, mockFramework);

            string unitTestContents = this.GenerateUnitTestContents(context);

            string testFolder = Path.GetDirectoryName(targetFilePath);

            if (File.Exists(targetFilePath))
            {
                throw new InvalidOperationException("Test file already exists.");
            }

            if (!Directory.Exists(testFolder))
            {
                Directory.CreateDirectory(testFolder);
            }

            File.WriteAllText(targetFilePath, unitTestContents);
        }
Beispiel #9
0
        private string GenerateUnitTestContents(TestGenerationContext context)
        {
            TestFramework testFramework = context.TestFramework;
            MockFramework mockFramework = context.MockFramework;

            string fileTemplate   = StaticBoilerplateSettings.GetTemplate(testFramework, mockFramework, TemplateType.File);
            string filledTemplate = StringUtilities.ReplaceTokens(
                fileTemplate,
                (tokenName, propertyIndex, builder) =>
            {
                switch (tokenName)
                {
                case "UsingStatements":
                    WriteUsings(builder, context);
                    break;

                case "Namespace":
                    builder.Append(context.UnitTestNamespace);
                    break;

                case "MockFieldDeclarations":
                    WriteMockFieldDeclarations(builder, context);
                    break;

                case "MockFieldInitializations":
                    WriteMockFieldInitializations(builder, context);
                    break;

                case "ExplicitConstructor":
                    WriteExplicitConstructor(builder, context, FindIndent(fileTemplate, propertyIndex));
                    break;

                case "ClassName":
                    builder.Append(context.ClassName);
                    break;

                case "ClassNameShort":
                    builder.Append(GetShortClassName(context.ClassName));
                    break;

                case "ClassNameShortLower":
                    // Legacy, new syntax is ClassNameShort.CamelCase
                    builder.Append(GetShortClassNameLower(context.ClassName));
                    break;

                default:
                    // We didn't recognize it, just pass through.
                    builder.Append($"${tokenName}$");
                    break;
                }
            });

            SyntaxTree tree          = CSharpSyntaxTree.ParseText(filledTemplate);
            SyntaxNode formattedNode = Formatter.Format(tree.GetRoot(), CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace);

            return(formattedNode.ToFullString());
        }
        private void WriteUsings(StringBuilder builder, TestGenerationContext context)
        {
            List <string> namespaces = new List <string>();

            namespaces.AddRange(context.MockFramework.UsingNamespaces);
            namespaces.Add(context.TestFramework.UsingNamespace);
            namespaces.Add(context.ClassNamespace);

            if (context.TestFramework.TestCleanupStyle == TestCleanupStyle.Disposable)
            {
                namespaces.Add("System");
            }

            foreach (InjectableType injectedType in context.InjectedTypes)
            {
                namespaces.AddRange(injectedType.TypeNamespaces);
            }

            foreach (TypeDescriptor argumentDescriptor in
                     context.MethodDeclarations.SelectMany(
                         d => d.MethodParameters.Select(p => p.TypeInformation)))
            {
                if (argumentDescriptor is InjectableType injectableType)
                {
                    namespaces.AddRange(injectableType.TypeNamespaces);

                    continue;
                }

                namespaces.Add("System");
            }

            if (context.MethodDeclarations.Any(m => m.IsAsync))
            {
                namespaces.Add("System.Threading.Tasks");
            }

            string extraNamespacesSetting = this.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.ExtraUsingNamespaces);

            string[] extraNamespaces = extraNamespacesSetting.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            namespaces.AddRange(extraNamespaces);

            namespaces = namespaces.Distinct().ToList();
            namespaces.Sort(StringComparer.Ordinal);

            for (int i = 0; i < namespaces.Count; i++)
            {
                builder.Append($"using {namespaces[i]};");

                if (i < namespaces.Count - 1)
                {
                    builder.AppendLine();
                }
            }
        }
        private void WriteExplicitConstructor(StringBuilder builder, TestGenerationContext context, string currentIndent)
        {
            builder.Append($"new {context.ClassName}");

            if (context.ConstructorTypes.Count > 0)
            {
                builder.AppendLine("(");

                for (int i = 0; i < context.ConstructorTypes.Count; i++)
                {
                    string         mockReferenceStatement;
                    InjectableType constructorType = context.ConstructorTypes[i];
                    if (constructorType == null)
                    {
                        mockReferenceStatement = "TODO";
                    }
                    else
                    {
                        string template = this.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.MockObjectReference);
                        mockReferenceStatement = ReplaceInterfaceTokens(template, constructorType, context);
                    }

                    builder.Append($"{currentIndent}    {mockReferenceStatement}");

                    if (i < context.ConstructorTypes.Count - 1)
                    {
                        builder.AppendLine(",");
                    }
                }

                builder.Append(")");
            }
            else if (context.Properties.Count == 0)
            {
                builder.Append("()");
            }

            if (context.Properties.Count > 0)
            {
                builder.AppendLine();
                builder.AppendLine("{");

                foreach (InjectableProperty property in context.Properties)
                {
                    string template = this.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.MockObjectReference);
                    string mockReferenceStatement = ReplaceInterfaceTokens(template, property, context);

                    builder.AppendLine($"{property.PropertyName} = {mockReferenceStatement},");
                }

                builder.Append(@"}");
            }
        }
        public async Task <string> GenerateUnitTestFileAsync(
            ProjectItemSummary selectedFile,
            EnvDTE.Project targetProject,
            TestFramework testFramework,
            MockFramework mockFramework)
        {
            string sourceProjectDirectory = Path.GetDirectoryName(selectedFile.ProjectFilePath);
            string selectedFileDirectory  = Path.GetDirectoryName(selectedFile.FilePath);

            if (sourceProjectDirectory == null || selectedFileDirectory == null || !selectedFileDirectory.StartsWith(sourceProjectDirectory, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Error with selected file paths.");
            }

            string relativePath = this.GetRelativePath(selectedFile);

            TestGenerationContext context = await this.CollectTestGenerationContextAsync(selectedFile, targetProject, testFramework, mockFramework);

            string unitTestContents = this.GenerateUnitTestContents(context);

            string testFolder = Path.Combine(Path.GetDirectoryName(targetProject.FullName), relativePath);

            string testFileNameBase = StringUtilities.ReplaceTokens(
                this.Settings.FileNameTemplate,
                (tokenName, propertyIndex, builder) =>
            {
                if (WriteGlobalToken(tokenName, builder, context))
                {
                    return;
                }

                WriteTokenPassthrough(tokenName, builder);
            });

            testFileNameBase = FileUtilities.CleanFileName(testFileNameBase);

            string testPath = Path.Combine(testFolder, testFileNameBase + ".cs");

            if (File.Exists(testPath))
            {
                throw new InvalidOperationException("Test file already exists.");
            }

            if (!Directory.Exists(testFolder))
            {
                Directory.CreateDirectory(testFolder);
            }

            File.WriteAllText(testPath, unitTestContents);

            return(testPath);
        }
        private static string CreateUniqueTestMethodName(TestGenerationContext context, string baseTestMethodName)
        {
            string testMethodName = baseTestMethodName;

            int j = 1;

            while (context.UsedTestMethodNames.Contains(testMethodName))
            {
                testMethodName = baseTestMethodName + j;
                j++;
            }

            return(testMethodName);
        }
Beispiel #14
0
        private void WriteExplicitConstructor(StringBuilder builder, TestGenerationContext context, string currentIndent)
        {
            builder.Append($"new {context.ClassName}");

            if (context.ConstructorTypes.Count > 0)
            {
                builder.AppendLine("(");

                for (int i = 0; i < context.ConstructorTypes.Count; i++)
                {
                    string         mockReferenceStatement;
                    InjectableType constructorType = context.ConstructorTypes[i];
                    if (constructorType == null)
                    {
                        mockReferenceStatement = "TODO";
                    }
                    else
                    {
                        mockReferenceStatement = CreateMockReferenceStatement(context, constructorType);
                    }

                    builder.Append($"{currentIndent}    {mockReferenceStatement}");

                    if (i < context.ConstructorTypes.Count - 1)
                    {
                        builder.AppendLine(",");
                    }
                }

                builder.Append(")");
            }
            else if (context.Properties.Count == 0)
            {
                builder.Append("()");
            }

            if (context.Properties.Count > 0)
            {
                builder.AppendLine();
                builder.AppendLine("{");

                foreach (InjectableProperty property in context.Properties)
                {
                    builder.AppendLine($"{property.PropertyName} = {CreateMockReferenceStatement(context, property)},");
                }

                builder.Append(@"}");
            }
        }
        // Works for both field declarations and initializations.
        private static void WriteFieldLines(StringBuilder builder, TestGenerationContext context, string template)
        {
            for (int i = 0; i < context.InjectedTypes.Count; i++)
            {
                InjectableType injectedType = context.InjectedTypes[i];
                string         line         = ReplaceInterfaceTokens(template, injectedType, context);

                builder.Append(line);

                if (i < context.InjectedTypes.Count - 1)
                {
                    builder.AppendLine();
                }
            }
        }
Beispiel #16
0
        private static string CreateMockReferenceStatement(TestGenerationContext context, InjectableType injectedType)
        {
            string template;

            if (context.Settings.CustomMocks.ContainsKey(injectedType.FullName))
            {
                template = context.Settings.CustomMockObjectReferenceTemplate;
            }
            else
            {
                template = context.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.MockObjectReference);
            }

            return(ReplaceInterfaceTokens(template, injectedType, context));
        }
Beispiel #17
0
        private static void WriteDefaultTestMethod(StringBuilder builder, TestGenerationContext context, string testedObjectCreation)
        {
            builder.AppendLine($"[{context.TestFramework.TestMethodAttribute}]");
            builder.AppendLine($"public void TestMethod1()");
            builder.AppendLine("{");
            builder.AppendLine("// Arrange");
            builder.AppendLine(testedObjectCreation);
            builder.AppendLine();             // Separator

            builder.AppendLine("// Act");
            builder.AppendLine();             // Separator

            builder.AppendLine("// Assert");
            builder.AppendLine(context.TestFramework.AssertFailStatement);
            builder.Append("}");
        }
        private static void WriteTodoConstructor(StringBuilder builder, TestGenerationContext context)
        {
            builder.Append("new ");
            builder.Append(context.ClassName);
            builder.Append("(");

            for (int i = 0; i < context.ConstructorTypes.Count; i++)
            {
                builder.Append("TODO");
                if (i < context.ConstructorTypes.Count - 1)
                {
                    builder.Append(", ");
                }
            }

            builder.Append(")");
        }
Beispiel #19
0
        private string ReplaceAllowedTokens(TestGenerationContext context, TemplateType templateType, IList <TokenEvaluator> allowedTokenEvaluators)
        {
            string templateValue = this.Settings.GetTemplate(
                context.TestFramework,
                context.MockFramework,
                templateType);

            return(StringUtilities.ReplaceTokens(
                       templateValue,
                       (tokenName, propertyIndex, builder) =>
            {
                foreach (var tokenEvaluator in allowedTokenEvaluators)
                {
                    if (tokenEvaluator.CanExecute(tokenName))
                    {
                        builder.Append(tokenEvaluator.Evaluate());
                        return;
                    }
                }

                WriteTokenPassthrough(tokenName, builder);
            }));
        }
Beispiel #20
0
        public async Task <string> GenerateUnitTestFileAsync(
            ProjectItemSummary selectedFile,
            EnvDTE.Project targetProject,
            TestFramework testFramework,
            MockFramework mockFramework)
        {
            string sourceProjectDirectory = Path.GetDirectoryName(selectedFile.ProjectFilePath);
            string selectedFileDirectory  = Path.GetDirectoryName(selectedFile.FilePath);

            if (sourceProjectDirectory == null || selectedFileDirectory == null || !selectedFileDirectory.StartsWith(sourceProjectDirectory, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Error with selected file paths.");
            }

            string relativePath = this.GetRelativePath(selectedFile);

            TestGenerationContext context = await this.CollectTestGenerationContextAsync(selectedFile, targetProject, testFramework, mockFramework);

            string unitTestContents = this.GenerateUnitTestContents(context);

            string testFolder = Path.Combine(Path.GetDirectoryName(targetProject.FullName), relativePath);
            string testPath   = Path.Combine(testFolder, context.ClassName + "Tests.cs");

            if (File.Exists(testPath))
            {
                throw new InvalidOperationException("Test file already exists.");
            }

            if (!Directory.Exists(testFolder))
            {
                Directory.CreateDirectory(testFolder);
            }

            File.WriteAllText(testPath, unitTestContents);

            return(testPath);
        }
        private bool WriteTestMethodInvocationToken(string tokenName, int propertyIndex, StringBuilder builder, TestGenerationContext context, string testTemplate, MethodDescriptor methodDescriptor)
        {
            int numberOfParameters = methodDescriptor.MethodParameters.Count();

            switch (tokenName)
            {
            case "TestedMethodName":
                builder.Append(methodDescriptor.Name);

                break;

            case "TestMethodName":
                this.WriteTestMethodName(builder, context, methodDescriptor);
                break;

            case "AsyncModifier":
                if (methodDescriptor.IsAsync)
                {
                    builder.Append("async");
                }

                break;

            case "AsyncReturnType":
                builder.Append(methodDescriptor.IsAsync ? "Task" : "void");
                break;

            case "ParameterSetupDefaults":
                WriteParameterSetupDefaults(builder, context, methodDescriptor);
                break;

            case "ParameterSetupTodo":
                for (int j = 0; j < numberOfParameters; j++)
                {
                    builder.Append($"{methodDescriptor.MethodParameters[j].TypeInformation} {methodDescriptor.MethodParameters[j].ArgumentName} = TODO;");

                    if (j < numberOfParameters - 1)
                    {
                        builder.AppendLine();
                    }
                }

                break;

            case "MethodInvocationPrefix":
                if (methodDescriptor.HasReturnType)
                {
                    builder.Append("var result = ");
                }

                if (methodDescriptor.IsAsync)
                {
                    builder.Append("await ");
                }

                break;

            case "MethodInvocation":
                WriteMethodInvocation(builder, methodDescriptor, FindIndent(testTemplate, propertyIndex));

                break;

            default:
                return(false);
            }

            return(true);
        }
Beispiel #22
0
        private string ReplaceTestedObjectCreationTokens(string testedObjectCreationTemplate, TestGenerationContext context)
        {
            return(StringUtilities.ReplaceTokens(
                       testedObjectCreationTemplate,
                       (tokenName, propertyIndex, builder) =>
            {
                if (WriteClassNameTokens(tokenName, builder, context))
                {
                    return;
                }

                if (tokenName == "ExplicitConstructor")
                {
                    this.WriteExplicitConstructor(builder, context, string.Empty);
                    return;
                }

                WriteTokenPassthrough(tokenName, builder);
            }));
        }
Beispiel #23
0
        private void WriteUsings(StringBuilder builder, TestGenerationContext context)
        {
            List <string> namespaces = new List <string>();

            namespaces.AddRange(context.MockFramework.UsingNamespaces);
            namespaces.Add(context.TestFramework.UsingNamespace);
            namespaces.Add(context.ClassNamespace);

            if (context.TestFramework.TestCleanupStyle == TestCleanupStyle.Disposable)
            {
                namespaces.Add("System");
            }

            IDictionary <string, string> customMocks = context.Settings.CustomMocks;

            foreach (InjectableType injectedType in context.InjectedTypes)
            {
                namespaces.AddRange(injectedType.TypeNamespaces);

                // Add in namespaces for custom mock if needed.
                if (customMocks.TryGetValue(injectedType.FullName, out string customMockClassFull))
                {
                    int lastDotIndex = customMockClassFull.LastIndexOf('.');
                    if (lastDotIndex > 0)
                    {
                        namespaces.Add(customMockClassFull.Substring(0, lastDotIndex));
                    }
                }
            }

            foreach (TypeDescriptor argumentDescriptor in
                     context.MethodDeclarations.SelectMany(
                         d => d.MethodParameters.Select(p => p.TypeInformation)))
            {
                if (argumentDescriptor is InjectableType injectableType)
                {
                    namespaces.AddRange(injectableType.TypeNamespaces);

                    continue;
                }

                namespaces.Add("System");
            }

            if (context.MethodDeclarations.Any(m => m.IsAsync))
            {
                namespaces.Add("System.Threading.Tasks");
            }

            string extraNamespacesSetting = context.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.ExtraUsingNamespaces);

            string[] extraNamespaces = extraNamespacesSetting.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            namespaces.AddRange(extraNamespaces);

            namespaces = namespaces.Distinct().ToList();
            namespaces.Sort(StringComparer.Ordinal);

            for (int i = 0; i < namespaces.Count; i++)
            {
                builder.Append($"using {namespaces[i]};");

                if (i < namespaces.Count - 1)
                {
                    builder.AppendLine();
                }
            }
        }
        private static string ReplaceInterfaceTokens(string template, InjectableType injectableType, TestGenerationContext context)
        {
            return(StringUtilities.ReplaceTokens(
                       template,
                       (tokenName, propertyIndex, builder) =>
            {
                if (WriteGlobalToken(tokenName, builder, context))
                {
                    return;
                }

                if (WriteInterfaceContentToken(injectableType, tokenName, builder))
                {
                    return;
                }

                WriteTokenPassthrough(tokenName, builder);
            }));
        }
Beispiel #25
0
        private void WriteTestMethods(StringBuilder builder, TestGenerationContext context)
        {
            string testedObjectReferenceTemplate = this.Settings.GetTemplate(
                context.TestFramework,
                context.MockFramework,
                TemplateType.TestedObjectReference);
            var testedObjectReference = this.ReplaceTestedObjectReferenceTokens(testedObjectReferenceTemplate, context);

            string testedObjectCreationTemplate = this.Settings.GetTemplate(
                context.TestFramework,
                context.MockFramework,
                TemplateType.TestedObjectCreation);
            var testedObjectCreation = this.ReplaceTestedObjectCreationTokens(testedObjectCreationTemplate, context);

            if (context.MethodDeclarations.Count == 0)
            {
                WriteDefaultTestMethod(builder, context, testedObjectCreation);

                return;
            }

            var usedTestMethodNames = new List <string>();

            for (int i = 0; i < context.MethodDeclarations.Count; i++)
            {
                var methodDescriptor   = context.MethodDeclarations[i];
                var baseTestMethodName = this.ReplaceAllowedTokens(
                    context,
                    TemplateType.TestMethodName,
                    new[] { new TestedMethodNameTokenEvaluator(methodDescriptor) });

                var testMethodName = CreateUniqueTestMethodName(usedTestMethodNames, baseTestMethodName);

                if (i > 0)
                {
                    builder.AppendLine();
                }

                string returnType = methodDescriptor.IsAsync ? "Task" : "void";

                string asyncModifier = methodDescriptor.IsAsync ? "async" : string.Empty;

                builder.AppendLine($"[{context.TestFramework.TestMethodAttribute}]");
                builder.AppendLine($"public {asyncModifier} {returnType} {testMethodName}()");
                builder.AppendLine("{");
                builder.AppendLine("// Arrange");
                builder.AppendLine(testedObjectCreation);
                var numberOfParameters = methodDescriptor.MethodParameters.Count();
                for (int j = 0; j < numberOfParameters; j++)
                {
                    builder.AppendLine($"{methodDescriptor.MethodParameters[j].TypeInformation} {methodDescriptor.MethodParameters[j].ArgumentName} = TODO;");
                }
                builder.AppendLine();                 // Separator

                builder.AppendLine("// Act");
                if (methodDescriptor.HasReturnType)
                {
                    builder.Append("var result = ");
                }

                if (methodDescriptor.IsAsync)
                {
                    builder.Append("await ");
                }

                builder.Append($"{testedObjectReference}.{methodDescriptor.Name}(");

                if (numberOfParameters == 0)
                {
                    builder.AppendLine(");");
                }
                else
                {
                    builder.AppendLine();

                    for (int j = 0; j < numberOfParameters; j++)
                    {
                        builder.Append($"	");
                        switch (methodDescriptor.MethodParameters[j].Modifier)
                        {
                        case ParameterModifier.Out:
                            builder.Append("out ");
                            break;

                        case ParameterModifier.Ref:
                            builder.Append("ref ");
                            break;

                        default:
                            break;
                        }
                        builder.Append($"{methodDescriptor.MethodParameters[j].ArgumentName}");

                        if (j < numberOfParameters - 1)
                        {
                            builder.AppendLine(",");
                        }
                        else
                        {
                            builder.AppendLine(");");
                        }
                    }
                }
                builder.AppendLine();                 // Separator

                builder.AppendLine("// Assert");
                builder.AppendLine(context.TestFramework.AssertFailStatement);
                builder.Append("}");

                if (i != context.MethodDeclarations.Count - 1)
                {
                    builder.AppendLine();
                }

                usedTestMethodNames.Add(testMethodName);
            }
        }
        private void WriteMockFieldInitializations(StringBuilder builder, TestGenerationContext context)
        {
            string template = this.Settings.GetTemplate(context.TestFramework, context.MockFramework, TemplateType.MockFieldInitialization);

            WriteFieldLines(builder, context, template);
        }
        private bool WriteContentToken(string tokenName, int propertyIndex, StringBuilder builder, TestGenerationContext context, string fileTemplate)
        {
            switch (tokenName)
            {
            case "UsingStatements":
                this.WriteUsings(builder, context);
                break;

            case "MockFieldDeclarations":
                this.WriteMockFieldDeclarations(builder, context);
                break;

            case "MockFieldInitializations":
                this.WriteMockFieldInitializations(builder, context);
                break;

            case "ExplicitConstructor":
                this.WriteExplicitConstructor(builder, context, FindIndent(fileTemplate, propertyIndex));
                break;

            case "TodoConstructor":
                WriteTodoConstructor(builder, context);
                break;

            case "TestMethods":
                this.WriteTestMethods(builder, context);
                break;

            default:
                return(false);
            }

            return(true);
        }
        private bool WriteTestMethodCommonToken(string tokenName, int propertyIndex, StringBuilder builder, TestGenerationContext context, string testTemplate)
        {
            switch (tokenName)
            {
            case "ExplicitConstructor":
                this.WriteExplicitConstructor(builder, context, FindIndent(testTemplate, propertyIndex));
                break;

            case "TodoConstructor":
                WriteTodoConstructor(builder, context);
                break;

            default:
                return(false);
            }

            return(true);
        }
        private static bool WriteGlobalToken(string tokenName, StringBuilder builder, TestGenerationContext context)
        {
            switch (tokenName)
            {
            case "Namespace":
                builder.Append(context.UnitTestNamespace);
                break;

            case "ClassName":
                builder.Append(context.ClassName);
                break;

            case "ClassNameShort":
                builder.Append(GetShortClassName(context.ClassName));
                break;

            case "ClassNameShortLower":
                // Legacy, new syntax is ClassNameShort.CamelCase
                builder.Append(GetShortClassNameLower(context.ClassName));
                break;

            default:
                return(false);
            }

            return(true);
        }
Beispiel #30
0
        private string ReplaceTestedObjectReferenceTokens(string testedObjectReferenceTemplate, TestGenerationContext context)
        {
            return(StringUtilities.ReplaceTokens(
                       testedObjectReferenceTemplate,
                       (tokenName, propertyIndex, builder) =>
            {
                if (WriteClassNameTokens(tokenName, builder, context))
                {
                    return;
                }

                WriteTokenPassthrough(tokenName, builder);
            }));
        }