0

I'm trying to write a convention test that specifies that a method should only be called in some contexts - specifically I have a static Empty getter that I only want to allow used in test methods, vis methods decorated with TestAttribute.

I know that I should also mark the getter as obsolete, use another method etc, but I also want a convention test around this so it doesn't break in the future.

I am guessing I want to use static analysis through reflection in my convention test. How would I go about performing this kind of analysis?

Rebecca Scott
  • 2,421
  • 2
  • 25
  • 39
  • 1
    Reflection won't provide implementation details (body) of your methods. You should use something similar to Roslyn. I suggest to add tag `roslyn` to your question, so that you will receive help from it's team, as Eric Lippert did with http://stackoverflow.com/questions/15891197/finding-everywhere-an-enum-is-converted-to-string – Ilya Ivanov May 06 '13 at 05:04

1 Answers1

1

Yes, Roslyn can help with this sort of thing. An example of what this might look like as a standalone analysis would be something like:

var solution = Solution.Load(pathToSolution);
foreach (var project in solution.Projects)
{
    var type = project.GetCompilation().GetTypeByMetadataName(typeNameContainingMethod);
    var method = type.GetMembers("Empty").Single();
    var references = method.FindAllReferences(solution);
    foreach (var referencedSymbol in references)
    {
        foreach (var referenceLocation in references)
        {
            CheckIfCallIsAllowed(referenceLocation);
        }
    }
}

You might also look at the Creating a Code Issue walkthrough and the Code Issue template that comes with the Roslyn CTP for another approach to doing this at edit time, instead of in a test.

Kevin Pilch
  • 11,485
  • 1
  • 39
  • 41