简体   繁体   English

使用反射测试抽象类的私有方法

[英]Testing private method of an abstract class using Reflection

How can I test a private method of an abstract class using reflection (using C#)? 如何使用反射(使用C#)测试抽象类的私有方法? I am specifically interested in adapting the code found in this thread . 我对修改此线程中的代码特别感兴趣。

I am aware of the discussion around the principle of testing private codes in the first place (one should not in general !!). 我知道围绕测试私有代码的原则进行的讨论(一般来说不应该这样!)。 I have already decided to do that for my situation because of various reasons, so let's not repeat those discussions. 由于各种原因,我已经决定针对我的情况进行此操作,因此,我们不再重复这些讨论。 Other SO threads (like Q# 1583363 and 1506427) discuss them in detail. 其他SO线程(例如Q#1583363和1506427)对其进行了详细讨论。 Thanks. 谢谢。

By definition, and abstract class cannot be instantiated, so you can't test it directly. 根据定义,抽象类无法实例化,因此无法直接对其进行测试。 You could use one of the mocking frameworks (like TypeMock . Otherwise, you'll need to create a concrete class that inherits from the abstract class, and use that for testing. 您可以使用其中一种模拟框架(例如TypeMock) 。否则,您需要创建一个从抽象类继承的具体类,并将其用于测试。

If your using VS2008 then it's as easy as right click your private method and selecting create unit test. 如果您使用的是VS2008,那么就像右键单击您的私有方法并选择创建单元测试一样容易。 VS will create a YourAbstractClass_Accessor class that will allow you to see and run that private method. VS将创建一个YourAbstractClass_Accessor类,该类将允许您查看和运行该私有方法。

Note: No additional mocking framework necessary. 注意:无需其他模拟框架。

You can do this, this is not reflection though, might be help for somebody. 您可以执行此操作,尽管这不是反映,但可能会对某人有所帮助。

var concreteClass = new concreteClass();
var po = new PrivateObject(concreteClass, new PrivateType(typeof(AbstractClass)));
Object[] args = new object[] {...};
po.Invoke("PrivateMethod", args);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM