Java 如何从另一个包中的超类测试受保护的继承方法

Java 如何从另一个包中的超类测试受保护的继承方法,java,Java,我有抽象类和子类: package myOtherPackage; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class AimpTest { @Test public void testProtectedMethodFromSuperClass(){ AImp aimp = new AImp();

我有抽象类和子类:

package myOtherPackage;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class AimpTest {
    @Test
    public void testProtectedMethodFromSuperClass(){
        AImp aimp = new AImp();
        assertEquals(aimp.get10Int().size(), 10);
    }
}
A.java:

package myPackage;

import java.util.ArrayList;
import java.util.List;

public abstract class A {

    protected abstract int getInt();

    protected List<Integer> get10Int() {
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < 10; i++){
            list.add(getInt());
        }
        return list;
    }
}
我在与子类相同的包中定义了一个测试:

package myOtherPackage;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class AimpTest {
    @Test
    public void testProtectedMethodFromSuperClass(){
        AImp aimp = new AImp();
        assertEquals(aimp.get10Int().size(), 10);
    }
}

我得到一个错误,因为
get10Int()
myPackage.A
中具有受保护的访问权限。有没有什么方法可以测试这个方法(它是另一个包中一个超类的继承方法),同时将
AImp
AImpTest
保存在
myOtherPackage
中,并将超类保存在自己的包中?

我会亲自为类a创建一个测试,在测试中,使用虚拟实现,然后测试您的函数。这样,就不需要在每个实现上都进行测试。

我同意另一个答案,即您应该为其包中的类
a
编写一个测试,因为您要测试的是
a
的功能,而不是
AImp
,但是如果您确实想访问受保护的(甚至是私有的)类方法您可以这样做:

@Test
    public void testProtectedMethodFromSuperClass(){
        AImp aimp = new AImp();

        Method get10IntMethod = AImp.class.getDeclaredMethod("get10Int");
        get10IntMethod.setAccessible(true);

        List<Integer> result = (List<Integer>) get10IntMethod.invoke(aimp);

        assertEquals(result.size(), 10);
    }
@测试
public void testProtectedMethodFromSuperClass(){
AImp AImp=新AImp();
方法get10IntMethod=AImp.class.getDeclaredMethod(“get10Int”);
get10IntMethod.setAccessible(true);
List result=(List)get10IntMethod.invoke(aimp);
assertEquals(result.size(),10);
}
如果您想调用带有参数的方法(例如,
otherMethod(int)
),则必须将参数类型传递给
getDeclaredMethod()
,如下所示:
getDeclaredMethod(“otherMethod”,int.class)
要调用的参数:
method.invoke(实例,5)

您不需要。测试你的类的可观察的外部行为。这些课程都没有。