InterviewSolution
| 1. |
How can we do testing for private methods? |
|
Answer» It is generally not required to test private methods directly. Since they are private, it is assumed that they are called from public methods. If these methods are working as expected, then by extension it is considered that the private methods are working correctly. HOWEVER, we can explore how the private methods are tested using REFLECTION. LET us consider we have a public class Item with private method getItemName() as shown below: public class Item { private STRING getItemName(String itemName) { //Some logic if(itemName.equals("computer")) { return itemName; } return "laptop"; }}Consider we have a test class ItemTest that tests this method as shown below: import static org.junit.Assert.assertEquals;import java.lang.reflect.Method;import org.junit.BeforeClass;import org.junit.Test;public class ItemTest { public static Item item; @BeforeClass public static VOID beforeClass() { item = new Item(); } @Test public void testGetItemNameSuccess() throws Exception { String expectedName = "computer"; Method method = Item.class.getDeclaredMethod("getItemName", String.class); method.setAccessible(true); String actualName = (String) method.invoke(item, actualName); assertEquals(expectedName, actualName); }}In the above code, we see that we can test the private method by using getDeclaredMethod method of the Method class that belongs to reflection strategy. Since we know that the private methods cant be invoked directly, we can use the Method class object’s invoke() method and send the input parameters. Then as usual, we can compare the results with the expected and the actual methods. |
|