1
private void ConvertString(ABC object) 
{
    String head = "";
    String tail="string_tail";
    if(!tail.isEmpty()) 
    {
        String converter = new StringConvert();
        head = converter.convert(tail, TYPE1);
        setHeadToTail(head,object);
    }
}

private void setHeadToTail(String head, ABC object) 
{
    List<Mixture> values=object.getValues();
    if (values!=null) 
    {
        for (Mixture Values1 : values) 
        {
            if (Values1 instanceof NumMixture) 
            {
                ((NumMixture) Values1 ).setTail(head);
            }
        }
     }

}

I want to write unit test for ConvertString method to check weather the value 'head' converted is equal to the value 'head' being passed in setHeadToTail(). Can anyone help in this?

@Test
public void test_ConvertedValue() throws Exception {

    ABC obj1=methodToSetSomeValues();
    Method method=Project.class.getDeclaredMethod("ConvertString", ABC.class);
    method.setAccessible(true);
    method.invoke(new Project(), obj1);
    String expectedVal= "1234";

    ArgumentCaptor<String> argumentCaptor=ArgumentCaptor.forClass(String.class);

    verifyPrivate(new Project()).invoke("setHeadToTail", argumentCaptor.capture(), obj1);
    assertEquals(expectedVal,argumentCaptor.getValue());


}

In this test case I want to check the value of 'head' converted is equal to parameter passed in setHeadToTail() i.e. head but this is not working.

SkyWalker
  • 28,384
  • 14
  • 74
  • 132
Sangeet
  • 145
  • 3
  • 9
  • What framework are you using for testing? – Vardaan Sharma Mar 04 '19 at 18:53
  • 4
    That simply does not matter. Your test is supposed to test the public API of your class, private methods do not matter. You need to properly test whoever calls `ConvertString` or extract it into a `Helper` class and mock an instance of it. – luk2302 Mar 04 '19 at 18:53

1 Answers1

2

I had the same question when I first started out. Basically, you can view a private method as just code as if it wasn't in a method at all; it's just there to make your code more readable or to remove boilerplate. So if you want to test the functionality, you need to test the method which is calling it.

public void someMethod() { // test this
    // some code
    privateMethod();
    // some more code
}

private void privateMethod() {
    // some code
}

When unit testing someMethod(), act as if the contents of privateMethod() are not in any method at all.

edit: In your case, it doesn't matter how many nested private methods you have, test the non-private method calling them all as if it were 1 large block of code.

Tiberiu
  • 990
  • 2
  • 18
  • 36