3

I have a class call ProductRegister that has a method

private List<Product> products = new CopyOnWriteArrayList<>();
void registerProduct(Product p) {
    products.add(p);
}

Bearing in mind products is private with no getter, and is created inside the class, how do I unit test this? I've considered adding a getter but isn't that exposing internal logic that I don't want others to know about?

TheCoder
  • 8,413
  • 15
  • 42
  • 54
  • Its private what do you want to test there? If indeed you need it, then the only way would be to mock out your list. However having said that, to make it testable, i would inject `List` rather than ProductRegister instantiate it. – SMA Feb 12 '17 at 09:22
  • @TheCoder the method doesn't seem to be doing much go be tested. That said, you can always mark the method as protected or with default access instead of making it as public. – Chetan Kinger Feb 12 '17 at 09:26
  • Presumably you have other methods for retrieving registered products? – ayahuasca Feb 12 '17 at 09:26
  • Possible duplicate of http://stackoverflow.com/questions/34571/how-do-i-test-a-class-that-has-private-methods-fields-or-inner-classes – JChrist Feb 12 '17 at 09:28
  • You can use reflection here is a good link with explanation http://stackoverflow.com/questions/34571/how-do-i-test-a-class-that-has-private-methods-fields-or-inner-classes – urag Feb 12 '17 at 09:30
  • @SMA I don't _need_ to test it but register is public and therefore I presumed it required test coverage to prove it works. – TheCoder Feb 12 '17 at 09:52

1 Answers1

3

You want to unit test your class ProductRegister, not the CopyOnWriteArrayList. So the question has to be how you can test if the method registerProduct(Product) does what it should do. You do not have a return value so I would test it in combination with another method. Maybe you have another method which returns the registered product so that you can assertTrue( <registeredProducts>.contains(product)) ?

edit: This way you won't have to change your JUnit-tests if you change the implementation (e.g. use another collection instead of CopyOnWriteArrayList).

Niklas P
  • 3,427
  • 2
  • 15
  • 19
  • This is exactly what I have - I have a method called getProducts(long id) that I will use in combination with register(); – TheCoder Feb 12 '17 at 11:04