tags:

views:

74

answers:

3

Hello I'm writting junit test how can I test this method .. this is only part of this method :

public MyClass{

public void myMethod(){
List<myObject> list = readData();
}
}

How will I make the test for this? ReadData is a private method inside MyClass?

+1  A: 

You can always test the List object to see if it contains all of the elements that readData() is supposed to insert into the list. Make a public method that returns the list and you can compare the length and elements in that list to what you are expecting to be in there.

amischiefr
A: 

Unless we know more about the method, all you really need to test is that the return from readData is in a format that fits into your generic list. Otherwise, its hard to recommend anything without knowing more about whats going on in your private method.

Jason M
A: 

As written, it doesn't make sense to test myMethod() unless readData() changes the instance state the way Frank Grimm mentioned. One thing to do would be to change myMethod() so that it puts list into a List instance variable. Then you might do something like this:

@Test
public void testThatReadDataReturnsACorrectList(){
   MyClass inst = new MyClass(); // Add args to ctor call if needed - maybe a file path that readData() will use?
   inst.myMethod();

   // Create a list of MyClasses that match what you expect readData() to return:
   List<MyClass> expectedList = new List<>();
   expectedList.Add(new MyClass(/* Some arguments */));
   expectedList.Add(new MyClass(/* Some more arguments */));
   expectedList.Add(new MyClass(/* Some other arguments */));

   // Assert that the list you created matches the list you get back from 
   assertArrayEquals("Did not get the list expected", expectedList.ToArray(), inst.getList().ToArray());

}

You'd still have to write MyClass.getList() to return the List instance variable.

To be robust, you could make the MyClass constructor accept an object that implements an interface like IMyReadInterface. readData() would use that object. Then in your test, you could instantiate a mock that also implements IMyReadInterface, configure the mock to provide the data needed so that readData() works correctly, and construct inst with that mock.

JeffH