1

I have searched everywhere and I can't find a way to test this type of method on how to write a Junit test on this method

Please

 private void AddToTable(String itemName, int itemQuantity){
    DefaultTableModel table = (DefaultTableModel)itemTable.getModel();
    String expiryDate = ((JTextField)jDateChooser2.getDateEditor().getUiComponent()).getText();
    String dateAdded = dtf.format(localDate);
    table.addRow(new Object[]{itemName, itemQuantity, dateAdded, "Date", expiryDate});
}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
codingmonk
  • 33
  • 3
  • I'm not sure if this method is a good candidate for unit testing, since the method depends on a number of fields that I assume are defined in the same class, and you're manipulating a Swing UI. In addition, it's a private method, so you can't access it outside of this class (such as in a unit test). Short version: in it's current form it's impossible. – Jeroen Steenbeeke Mar 15 '18 at 14:38
  • You can't directly test this method, you have to test it through the methods that use this method. – Stultuske Mar 15 '18 at 14:39
  • You could use something like mockito to assert that certain methods have been called a certain number of times. – Andreas Hartmann Mar 15 '18 at 14:40
  • Possible duplicate of [How do I test a private function or a class that has private methods, fields or inner classes?](https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or) – Vinay Prajapati Mar 15 '18 at 19:20

1 Answers1

1

This is a private method, you cannot test it directly and probably won't need to.

You could though test it indirectly by testing the method that calls it and checking the DefaultTableModel returned by itemTable.getModel() since it seems to be a field in your class and assuming you have a getter for it.

You should try to write code that is testable, for example having methods that are package protected, so that you can access them in your test class assuming the latter is in the same package and try to have methods return something, void methods are rather difficult to test, you can only test for their impact.

A4L
  • 17,353
  • 6
  • 49
  • 70