简体   繁体   English

如何通过反射调用抽象方法的受保护方法?

[英]How to invoke protected method of an abstract method by means of Reflection?

I'm trying to write a unit test for an abstract class. 我正在尝试为抽象类编写单元测试。 More specifically, I have a class like 更具体地说,我有一个像

public abstract class MyAbstractClass
{
    // ... 
    private Something _myPrivateVariable; 
    // ...
    protected void MyProtectedMethod(string[] names) { // ... }
    // ... 
}

and I want to call MyProtectedVoid with parameters and then verify that _myPrivateVariable was set to a particular value. 我想使用参数调用MyProtectedVoid ,然后验证_myPrivateVariable是否设置为特定值。

I know how to invoke a private method of an instance of a class using GetMethod like in How do I use reflection to invoke a private method? 我知道如何使用GetMethod 调用类实例的private方法,如如何使用反射来调用私有方法? , but I don't know how to do this type of thing with an abstract class considering that I can't create an instance of it. ,但考虑到我无法创建它的实例,因此我不知道如何使用abstract类来进行此类操作。

Suppose Caller is the class that is trying to call your protected method from abstract class. 假设Caller是试图从抽象类调用受保护方法的类。 In this case, you will have to inherit abstract class, since it will not allow you to create a new instance of it: 在这种情况下,您将必须继承抽象类,因为它将不允许您创建它的新实例:

public abstract class MyAbstractClass
  {
    // ... 
    private Something _myPrivateVariable; 
    // ...
    protected void MyProtectedMethod(string[] names) { // ... }
    // ... 
  }

public class Caller:MyAbstractClass // inheriting the abstract class
 {
     public void GetAbstractMethod(){
     MyProtectedMethod(/*string[] values*/);
     } 
  }

You can't call a method of a object that doesn't exist, and abstract classes, by themselves, can't be created. 您不能调用不存在的对象的方法,并且不能单独创建抽象类。

But you're actually trying to solve a fairly simple problem. 但是您实际上正在尝试解决一个相当简单的问题。 Because you just want to test the methods of the abstract class you can create a test class that inherits from the abstract class and "implements" any abstract methods by failing the test. 因为只想测试抽象类的方法,所以可以创建一个从抽象类继承的测试类,并通过使测试失败来“实现”任何抽象方法。 You can then use the test class to test abstract class and its protected methods and fields. 然后,您可以使用测试类来测试抽象类及其受保护的方法和字段。

public class MyAbstractTestClass : MyAbstractClass
{
    public void TestProtectedMethod(string[] names)
    {
        Assert...
        this.MyProtectedMethod(names);
        Assert...
    }
}

This lets you call the routines, gives you access to protected methods and fields, and because you declare the test class in your unit tests you don't affect other code. 这使您可以调用例程,使您可以访问受保护的方法和字段,并且由于在单元测试中声明了测试类,因此不会影响其他代码。 This approach will even catch some cases where the abstract base class changes without updating the test code. 这种方法甚至可以捕获抽象基类发生更改而无需更新测试代码的某些情况。

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

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