关于C#中反射的快速问题

时间:2009-03-27 19:01:02

标签: c# reflection nunit

我开始考虑测试驱动开发的概念,有点失败,因为我发现我知道测试会是什么样的,但我无法弄清楚如何让它去做我想要的是。我所拥有的是具有public getter和internal setter的属性。我想通过从单元测试中访问internal setter来测试功能,但我无法弄清楚如何做到这一点。这是测试:

    [Test()]
    public void HandleInput() {
        _requestType = _request.GetType();
        PropertyInfo propStdin =
            _requestType.GetProperty("StandardInput", BindingFlags.Public | BindingFlags.NonPublic);
        if(propStdin == null) {
            // Bug in the test.
            throw new Exception("There is a bug in the test. Reflection of stdin property returned null.");
        }
        MethodInfo setStdin = propStdin.GetSetMethod();

        // This will fail at the moment since nothing is here to make this happen.
        Assert.AreEqual("NewInputNewRequestInput", _request.StandardInput);
    }

现在,问题在于,当我运行测试时,我得到:

[mono-2.4] mbt@zest:~/Projects/StaffASAP/Test.FastCGI/bin/Debug$ nunit-console2 Test.FastCGI.dll
NUnit version 2.4.8
Copyright (C) 2002-2007 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.

Runtime Environment - 
   OS Version: Unix 2.6.29.0
  CLR Version: 2.0.50727.1433 ( Mono 2.4 )

..F
Tests run: 2, Failures: 1, Not run: 0, Time: 0.111 seconds

Test Case Failures:
1) Test.FastCGI.tRequest.HandleInput : System.Exception : There is a bug in the test. Reflection of stdin property returned null.
at Test.FastCGI.tRequest.HandleInput () [0x00051] in /home/mbt/Projects/StaffASAP/Test.FastCGI/tRequest.cs:54
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00057] in /media/disk/mono-2.4/sources/mono-2.4/mcs/class/corlib/System.Reflection/MonoMethod.cs:159

所以,我必须尝试错误地访问该属性,但从查看文档,我不知道我做错了什么。 我做错了什么?

3 个答案:

答案 0 :(得分:4)

你错过了吗? GetProperty(...)调用中的BindingFlags.Instance?

然而,通过InternalsVisibleTo属性将内部变量公开给测试程序会更好,因为您不需要依赖反射,如果测试项目是Visual Studio中解决方案的一部分,重构将会传播

答案 1 :(得分:2)

您可能需要查看InternalsVisibleTo汇编属性:

  

[Y]您可以将程序集的内部方法/属性/类公开给“朋友”程序集。通常,内部组件只能由同一程序集的成员访问,并且通常用于隐藏“管道”方法和实用程序类。

答案 2 :(得分:0)

Here is a similar article在SO上处理单元测试,内部成员和反思..