/// <summary> /// Creates a test file named 'SecuredTests.cs' that contains all the test methods. /// </summary> /// <param name="p_methods"></param> public static void CreateTestFile(Dictionary <TestingMethodVM, List <TestConfiguration> > p_methods) { DTE2 dte = (DTE2)Secure_TDDPackage.GetGlobalService(typeof(DTE)); Solution2 soln = (Solution2)dte.Solution; Project currentProj = dte.ActiveDocument.ProjectItem.ContainingProject; Project proj = GetTestingProject(currentProj); ProjectItem pi = GetCSTestFile(proj, soln); FileCodeModel2 fcm = (FileCodeModel2)pi.FileCodeModel; if (!IsContainImports(fcm)) { fcm.AddImport("System"); fcm.AddImport("System.Linq"); fcm.AddImport("System.Text"); fcm.AddImport("System.Collections.Generic"); fcm.AddImport("Microsoft.VisualStudio.TestTools.UnitTesting"); } string namespaceName = "Testing"; CodeNamespace testingNameSpace = GetNamespace(fcm, namespaceName); if (testingNameSpace != null) { string className = "SecuredTestClass"; CodeClass2 securedClass = GetClass(fcm, testingNameSpace, className); foreach (var methodKeyValue in p_methods) { var startIndexOfMethodName = methodKeyValue.Key.FullName.LastIndexOf('.'); var methodBaseName = methodKeyValue.Key.FullName.Substring(startIndexOfMethodName + 1) + "_{0}Test"; foreach (var testConfiguration in methodKeyValue.Value) { // Remove all white-spaces in the test name. var fixedName = testConfiguration.Name.Replace(" ", string.Empty); var methodName = string.Format(methodBaseName, fixedName); var functionBody = GetMethodBody(methodKeyValue.Key, testConfiguration); AddFunction(securedClass, methodName, functionBody); } } } // if the file is not opened in the text editor, open and activate it. Window window = pi.Open(Constants.vsViewKindCode); if (window != null) { window.Activate(); dte.ExecuteCommand("Edit.FormatDocument"); } // Save the file. pi.Save(); }
private static Project GetTestingProject(Project p_referencedProject) { Project testingProject = null; string projectName = "UnitTesting"; DTE2 dte = (DTE2)Secure_TDDPackage.GetGlobalService(typeof(DTE)); Solution2 soln = (Solution2)dte.Solution; foreach (Project proj in soln.Projects) { if (proj.Name == projectName) { testingProject = proj; break; } } if (testingProject == null) { string unitTestProjectTemplatePath; unitTestProjectTemplatePath = soln.GetProjectTemplate("UnitTestProject", "CSharp"); string projectDestinationPath = soln.FullName.Remove(soln.FullName.LastIndexOf('\\')); projectDestinationPath += "\\" + projectName; soln.AddFromTemplate(unitTestProjectTemplatePath, projectDestinationPath, projectName); foreach (Project proj in soln.Projects) { if (proj.Name == projectName) { testingProject = proj; break; } } VSProject vsProj = testingProject.Object as VSProject; vsProj.References.AddProject(p_referencedProject); } return(testingProject); }