سؤال

The context of this question is too elaborate to describe here and will likely adversely affect responses so I am not including it. I want to assert certain things about a method in a unit test. Some of these things are possible using reflection such as format of the try/finally block, class fields and method local variables, etc. I already know the type and method signature.

    protected override void OnTest ()
    {
        bool result = false;
        SomeCOMObject com = null; // System.__ComObject

        try
        {
        }
        finally
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(com);
        }

        return (result);
    }

What I have not been able to achieve are things like:

  • Whether the method contains only a single return (result); statement and whether that statement is the last one in the function.
  • Whether all variables of type System.__ComObject have been manually de-referenced using System.Runtime.InteropServices.Marshal.ReleaseComObject(object) in the finally block.

Since some of these things are not possible using reflection, and source code text analysis is far from ideal, I turned to CodeDom but have not been able to get a grip on it. I have been told that creating expression trees from source code is not possible. Nor is it possible to create expression trees from the runtime type. If that is correct, how can I leverage CodeDom to achieve things in the list above?

I have used CodeDom in the past for code generation and compiling simple code classes to assemblies. But I have no idea how it could be used to analyze the internals of a method. Please advise.

هل كانت مفيدة؟

المحلول

In general, reflection built into programming languages provides no access to the content of functions. So you pretty much can't do this with reflection.

You might be able to do it if you have access to the byte-code equivalent, but byte code can't really answer questions about the syntax of the method, e.g., "how many return statements exists returning the same expression".

If you want to reason about code, your need to reason about the source code. This means you need access to a parser, and often other useful facts ("what the declaration of X?", "Is the type of X and Y compatible?", "Does data flow from X to Y?"), etc.

Roslyn provides some of this information. There are also commercial solutions (I have one).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top