How do I test a class that has private methods, fields or inner classes?

To test a class that has private methods, fields, or inner classes, you can do the following:

  1. Write public methods in the class that call the private methods, fields, or inner classes and use those public methods to test the private ones.

  2. Use reflection to access the private methods, fields, or inner classes and test them directly.

  3. Use the PowerMock library, which allows you to test private methods, fields, or inner classes.

Here's an example of how you could test a private method using the first approach:

public class MyClass {
   private void privateMethod() {
     // implementation goes here
   }

   public void testPrivateMethod() {
     privateMethod();
   }
}

// test
@Test
public void testPrivateMethod() {
   MyClass myClass = new MyClass();
   myClass.testPrivateMethod();
   // assert the desired behavior of the private method
}

Here's an example of how you could test a private field using the second approach:

public class MyClass {
   private int privateField;

   public void setPrivateField(int value) {
      privateField = value;
   }

   public int getPrivateField() {
      return privateField;
   }
}

// test
@Test
public void testPrivateField() throws Exception {
   MyClass myClass = new MyClass();
   Field privateField = MyClass.class.getDeclaredField("privateField");
   privateField.setAccessible(true);
   privateField.set(myClass, 42);
   assertEquals(42, myClass.getPrivateField());
}

I hope this helps! Let me know if you have any other questions.