public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; // Find the type declaration identified by the diagnostic. var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <ClassDeclarationSyntax>().First(); try { // Register a code action that will invoke the fix. context.RegisterCodeFix( CodeAction.Create( title: title, createChangedDocument: c => _xUnitSetupGenerator.RegenerateSetup(context.Document, declaration, c), equivalenceKey: title), diagnostic); } catch { } }
public async Task RewritesDefaultConstructor(string filePath) { // Arrange var filePathClassUnderTest = "files.ClassUnderTest.txt"; var filePaths = new[] { filePath, filePathClassUnderTest }; var documents = DocumentProvider.CreateCompilationAndReturnDocuments(filePaths); var documentWithTestClass = documents[filePath]; var root = await documentWithTestClass.GetSyntaxRootAsync(); var testClass = root.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().First(); var documentWithClassUnderTest = documents[filePathClassUnderTest]; var classUnderTest = SyntaxNodeProvider.GetSyntaxNodeFromDocument <ClassDeclarationSyntax>(documentWithClassUnderTest, "ClassUnderTest"); var semanticModel = await documentWithClassUnderTest.GetSemanticModelAsync(); _classUnderTestFinder.Setup(_ => _.GetAsync(It.IsAny <Solution>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(new ClassUnderTest(classUnderTest, semanticModel)); // Act var actual = await _target.RegenerateSetup(documentWithTestClass, testClass, new CancellationToken()); // Assert var actualText = await actual.GetTextAsync(); _testOutput.WriteLine(actualText.ToString().Replace(";", ";\n")); var expected = await DocumentProvider.CreateDocumentFromFile("files.TestClass_WithFinalSetupConstructor.txt").GetTextAsync(); Assert.Equal(expected.ToString().RemoveWhitespace(), actualText.ToString().RemoveWhitespace()); }