1

So I have a class like this:

public class Person {
   private List<String> list = new ArrayList<String>();

   public addPerson(String s) {
        this.list.add(s);   
   }
}

public class TestPerson extends TestCase {
     private Person person;

     public testAddPerson() {
        this.person.addPerson("John");
     }    
}

My question is how can I test that John was added in the list. I woulod like to do some tests like list.size() == 1 or list.get(0).equals("John")

Any suggestions?

dres
  • 499
  • 6
  • 18
  • 1
    What is the external behaviour for having an item in `list`? Test that. – Michael Lloyd Lee mlk Nov 12 '15 at 12:28
  • 3
    This is a dup of http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes. However I disagree with the accepted answer. My answer would be don't. Test the public behaviour. – Michael Lloyd Lee mlk Nov 12 '15 at 12:29
  • It is a duplicate, but I would say that in some circumstances you might want to use reflection (Generally if it must be tested and the code is written in a way that it is impossible, and refactoring isn't an option), but for the example you gave just test the public behaviour and don't bother with reflection. – Seb Nov 12 '15 at 13:55

3 Answers3

0

You can use Reflection to test private variables.

But it might not be a good idea. It is recommended to test private properties trough public interfaces instead.

Luboš Turek
  • 6,273
  • 9
  • 40
  • 50
0

for this code testing makes no sense, it would actually test that the list implementation does what it supposed to be doing and that should not be part of your test.

The question is - where is your list used, where is any public access to it, and what behavior is there expected. This what you should test.

Overall, this sounds like test-after where you try to add tests for the sake of testing and not for verification.

Emerson Cod
  • 1,990
  • 3
  • 21
  • 39
0

There is a very useful tool for this called shazamcrest. It serializes actual and expected objects to json and does String comparison. You don't have to modify your production code (no annotations, no getters needed, fields can be private).

assertThat(actualPerson, sameBeanAs(expectedPerson));

And it throws ComparisonFailure so you get very good diagnostics like this:

enter image description here

Jaroslaw Pawlak
  • 5,538
  • 7
  • 30
  • 57