访问抽象测试类内部的接口的私有字段

时间:2018-10-24 19:22:01

标签: java unit-testing

我有一个抽象的基础测试类和一个接口。在测试类内部,声明了类型为interface的私有字段。

abstract class FibonacciTest {
  *private FibonacciImplementation fibonacciImplementation;*

   public FibonacciImplementation getImplementation(){
       return this.fibonacciImplementation;
   }
   protected void setImplementation(FibonacciImplementation fibimplem){
       this.fibonacciImplementation = fibimplem;
   }
  abstract void createFibonacciImplementation();

  @BeforeEach
  void createImplementation(){
    createFibonacciImplementation();
  }

  @Test
  void invalidPosition(){
    assertEquals(new BigInteger("-2"),
      fibonacciImplementation.calculateFib(-2));
  }

界面为:

public interface FibonacciImplementation {
  BigInteger calculateFib(int position);
}

基本测试类的子测试类是这样的:

public class RecursiveFibonacciTest extends FibonacciTest{

  @BeforeEach
  void createFibonacciImplementation(){
    fibonacciImplementation = new RecursiveFibonacciImplementation();* error is here
  }
}

refisivefibonacciImplentation是这样的:

public class RecursiveFibonacciImplementation implements FibonacciImplementation {

  @Override
  public BigInteger calculateFib(int position) {

    if(position < 0 )
      return new BigInteger("" + position);
    if(position == 1 || position == 0)
      return new BigInteger("1");

    return calculateFib(position-1).add(calculateFib(position-2));
  }
}

我遇到的问题是,在子测试类中,编译器抱怨我试图访问私有字段。 private FibonacciImplementation fibonacciImplementation;字段。我该如何消除该错误。如何访问fibonacciImplementation?该getter和setter方法似乎无效。编译器显示fibonacciImplementation has private access in FibonacciTest

请记住,要求它必须是一个私有字段。

2 个答案:

答案 0 :(得分:1)

您真的需要一个字段吗?如果创建实现类的实例并不昂贵,则仅在需要时才可以获取实例,而无需将其存储在字段中。

abstract class FibonacciTest {

  abstract FibonacciImplementation createFibonacciImplementation();

  @Test
  void invalidPosition(){
    assertEquals(new BigInteger("-2"),
      createFibonacciImplementation().calculateFib(-2));
  }

}


public class RecursiveFibonacciTest extends FibonacciTest{

  @Override
  FibonacciImplementation createFibonacciImplementation(){
    return new RecursiveFibonacciImplementation();
  }

}

答案 1 :(得分:0)

private表示只能从同一类中进行访问。如果您只想让子类访问某个字段,则需要将其标记为protected

更改此:

private FibonacciImplementation fibonacciImplementation;

对此:

protected FibonacciImplementation fibonacciImplementation;

FibonacciTest类中。