简体   繁体   中英

Testing a private method in Java

I am a beginner in programming in Java. I am facing a problem in testing a private method against a unit testing tool. There are no errors when I compile and I am getting the expected results when I enter the values in the fields.

Here is the part of the code I wrote:

public class Title {
     private String getNewString() {
        if (newName == null || "".equals(newName)) {
            return newName;
        } else {
            return (newName.substring(0,1).toUpperCase() + newName.substring(1).toLowerCase());
        }
    }
}

The following is the testing tool which is giving me the error: <method> does not exist, or is spelled wrong

@Test
public void TestGetNewString() {

    //String parameter
    Class[] paramString = new Class[1]; 
    paramString[0] = String.class;

    try {
        //load the Title at runtime
        Class cls = Class.forName("Title");
        Object obj = cls.newInstance();

        //call the printItString method, pass a String param 
        Method method = cls.getDeclaredMethod("getNewString", paramString);
        method.setAccessible(true);
        String returnVal1 = (String) method.invoke(obj, new String("Peter"));
        String returnVal2 = (String) method.invoke(obj, new String("PETER"));
        String returnVal3 = (String) method.invoke(obj, new String("PeTEr"));
        int modifiers = method.getModifiers();

        assertEquals("getNewString does not format the name correctly. \n", "Peter", returnVal1);
        assertEquals("getNewString does not format the name correctly.  \n", "Peter", returnVal2);
        assertEquals("getNewString does not format the name correctly.  \n", "Peter", returnVal3);
        assertEquals("Method \"getNewString()\" is not marked private.  \n", true, Modifier.isPrivate(modifiers));
    } catch (NoSuchMethodException e) { // Field does not exist
        throw new AssertionError("Method \"getNewString()\" does not exist, or is spelled wrong.  \n");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Any suggestions as to where I am making a mistake?

Your method is calling:

 Method method = cls.getDeclaredMethod("getNewString", paramString);

and you define paramString as:

 Class[] paramString = new Class[1]; 

This would mean that it looks for a method signature that uses one parameter. getNewString however doesn't have any parameters.

Removing paramString should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM