0

I've written a CodeAnalyzer/CodeFix using VS Community 17.4.3, and I'm trying to test them with the Visual Studio generated unit test code. The analyzer text runs successfully, and the CodeFix produces what appears to be a valid modified document. However, the CodeFix test fails because CodeFixTest<TVerifier>.FixEachAnalyzerDiagnosticAsync() returns an error. Specifically, the failure is caused by

                        var fixedProject = await ApplyCodeActionAsync(project, actionToApply, verifier, cancellationToken).ConfigureAwait(false);
                        if (fixedProject != project)
                        {
                            done = false;
                            project = fixedProject;
                            break;
                        }

because the fixedProject and project are not equal.

I'm a bit lost trying to resolve this because no real projects are involved. The test is using hardcoded strings as both input and expected output.

I've validated the output from the CodeFix equals the expected modification fed to the unit test. I was expecting the unit test to succeed.

2
  • I should is that probing with the debugger has yet to yield any difference between content in the two projects. Commented Dec 21, 2022 at 17:23
  • Debugging of ApplyCodeActionAsync shows the CodeFix is invoked as expected, but the resulting Solution contains a project without the Document modification. Commented Dec 21, 2022 at 19:49

1 Answer 1

1

There was a problem with my altered document after all. This is perhaps a 'newbie' issue writing CodeFix.

My CodeFix imposes a custom sort order on the UsingDirectives in the code under analysis. I extracted the Usings from the CompilationUnitSyntax, cloned each UsingDirective, then sorted them into the desired order. I then replaced the UsingDirectives in the CompilationUnitSyntax in a 'for' loop using ReplaceNode as shown in Microsoft documentation samples.

My replacement loop I believe ran afoul of a classic List (in this case SyntaxList) update problem. After the first replacement, I transiently had two Directives in the CompilationSyntax that had the same 'NameSyntax' due to the sequential replacement algorithm I used. I got no errors, the replacement ran to completion, but the resulting SyntaxTree was not my desired state. Whether this is a bug or feature of ReplaceNode I don't know.

I removed my iterative replacement loop and used CompilationUnitSyntax.WithUsing(SyntaxList) to replace all of the usings at once, using my sorted List to create the SyntaxList. Viola!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.