简体   繁体   中英

Testing class with ArrayList private member

I have a Java class with following implementation:

    class Some {
      private ArrayList<SomeObject> list = new...

      public void addToList(Long t) {
          SomeObject so = new SomeObject(new Date, t)
          list.add(so)
      } 

      private float fun1(ArrayList<SomeObject> x) {
      //some operations on list "list", 
      //res - result of float calculations based on list "x"
      return res
      }

      public float publicFun() {
         //some other operations on private list "list"
         return fun1(list);
      }

The question is how to test function publicFun() using Mockito, PowerMock or other testing tool ? To run this public function I have to mock private List but how can I do it ?

In this example there are several problems caused by unwelcome dependencies:

1 new Date() To solve it I suggest to introduce new interface

interface CurrentTimeProvider {
    Date getCurrentDate();
}

Implementation is obvious (I skip it for briefness)

2 Is new ArrayList()

  • You can replace it with you own interface (containing only method you need)
  • You can mock ArrayList itself
  • You can use real impl of ArrayList and test it altogether

In result we get something like this:

class Some {
  private CurrentTimeProvider timeProvider;
  private ArrayList<SomeObject> list = new ArrayList<SomeObject>();

  public void setTimeProvider(CurrentTimeProvider timeProvider) {
      this.timeProvider = timeProvider;
  }

  public void addToList(Long t) {
      SomeObject so = new SomeObject(timeProvider.getCurrentDate(), t)
      list.add(so)
  } 

  public float publicFun() {
     //some other operations on private list "list"
     return fun1(list);
  }

And test look look this:

CurrentTimeProvider timeProvider = mock(CurrentTimeProvider.class);
Some some = new Some();
some.setTimeProvider(timeProvider);

when(timeProvider.getCurrentDate).thenReturn(mock(Date.class));

//Invoke you method
some.publicFun();

//Put assert and verify here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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