There are two methods to test PRIVATE:
1) Change the private method (modifier: Private) of the target class to (public ),Not recommended,The source program is not well modified.
2) through reflection (Recommendation)
Code Demonstration:
Target Program
Privatemethod. Java
Package COM. junit3_8; </P> <p> public class privatemethod {<br/> // Private method <br/> private int add (int A, int B) <br/>{< br/> return a + B; </P> <p >}< br/>
Test procedure
Privatemethodtest. Java
Package COM. junit3_8; </P> <p> Import Java. lang. reflect. method; </P> <p> Import JUnit. framework. assert; <br/> Import JUnit. framework. testcase; </P> <p>/** <br/> * test the private method through reflection, <br/> */<br/> public class privatemethodtest extends testcase {</P> <p> Public void testadd () throws exception <br/>{< br/> // privatemethod PM = new privatemethod (); <br/> // obtain the Class Object of the target class <br/> class <privatemethod> class1 = privatem Ethod. class; </P> <p> // obtain the instance of the target class <br/> object instance = class1.newinstance (); </P> <p> // getdeclaredmethod () public, protected, default (Package) Access, and private methods can be obtained, but not inherited methods. <Br/> // getmethod () can only obtain public methods <br/> method = class1.getdeclaredmethod ("add", new class [] {Int. class, Int. class}); </P> <p> // when the value is true, the reflected object should cancel all existing access permissions during use. <br/> method. setaccessible (true); </P> <p> Object result = method. invoke (instance, new object [] {1, 2}); </P> <p> assert. assertequals (3, result); </P> <p >}< br/>
Summary:
Getdeclaredmethod () can obtain public, protected, default (Package) Access, and private methods, but does not include inherited methods.
Getmethod () can only obtain public methods
Method method = class1.getdeclaredmethod ("add", new class [] {Int. Class, Int. Class });
Equivalent
Method method = class1.getdeclaredmethod ("add", new class [] {INTEGER. type, Int. Integer. Type });
Because
Integer. type indicates the basic type.
intOfClassInstance