0

I'm facing to a similar kind of scenario as described below. Since I'm unable to share the actual code I'm using that.

I'm trying to test the addToList() method in the below class.

public class MyClass{

    private List<String> nameList = new ArrayList<String>();

    public void addToList(String name){
        nameList.add(name);
    }
}

I want to check whether the list get updated by calling the addToList() method. (nameList.size() check is enough)

I'm writing JUnits and can't figure out a way to access that nameList after calling the method.

   @Test
   public void test() {
      MyClass my = new MyClass();
      my.addToList("one");
      my.addToList("two");

      // how to check the 'nameList' to complete the test
   }

May be Reflections can be the solution for this, but still it is unclear.

What is the best way to do that (without changing the actual class).

prime
  • 14,464
  • 14
  • 99
  • 131
  • And hint: the reasonable way is **not** reflection; but to use dependency injection to **provide** a list to your class under test. – GhostCat Mar 30 '17 at 09:48
  • Can you please elaborate. – prime Mar 30 '17 at 09:49
  • You got a lot of information in that linked DUP question; and google has a lot of hits for such terms, such as http://www.javaranch.com/journal/200709/dependency-injection-unit-testing.html – GhostCat Mar 30 '17 at 10:31

0 Answers0