Created
May 17, 2017 09:32
-
-
Save Wolfsblvt/1420c4ddd11f9386cb3ab2dadff313cb to your computer and use it in GitHub Desktop.
Class tot test refactoring option to add test project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Composition; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CodeActions; | |
using Microsoft.CodeAnalysis.CodeRefactorings; | |
using Microsoft.CodeAnalysis.CSharp.Syntax; | |
namespace TestsCreatorCommandss | |
{ | |
[ExportCodeRefactoringProvider(RefactoringId, LanguageNames.CSharp)] | |
[Shared] | |
internal class TestsCreatorCommands : CodeRefactoringProvider | |
{ | |
public const string RefactoringId = "CreateEmptyTest"; | |
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) | |
{ | |
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(continueOnCapturedContext: false); | |
var node = root.FindNode(context.Span); | |
var dec = node as MethodDeclarationSyntax; | |
if (dec == null) | |
return; | |
context.RegisterRefactoring(CodeAction.Create("Create empty Test", c => CreateTest(context.Document, dec, c))); | |
} | |
private static async Task<Solution> CreateTest(Document document, MethodDeclarationSyntax method, CancellationToken cancellationToken) | |
{ | |
var solution = document.Project.Solution; | |
// Try to find existing test project | |
var projectName = document.Project.Name + ".UnitTests"; | |
var testProject = solution.Projects.FirstOrDefault(x => x.Name == projectName); | |
if (testProject == null) | |
{ | |
// Create the project and update the solution | |
testProject = solution.AddProject(projectName, projectName, LanguageNames.CSharp); | |
solution = testProject.Solution; | |
} | |
solution.Workspace.CanApplyChange(ApplyChangesKind.AddProject) | |
// Try to find existing test document | |
var documentName = $"{((TypeDeclarationSyntax) method.Parent).Identifier.Text}Tests.cs"; | |
var testDocument = testProject.Documents.FirstOrDefault(x => x.Name == documentName); | |
if (testDocument == null) | |
{ | |
// Create the document and update the project and solution | |
testDocument = testProject.AddDocument(documentName, "", document.Folders); | |
testProject = testDocument.Project; | |
solution = testProject.Solution; | |
} | |
return solution; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment