Application of Java reflection and annotation (Automatic Testing Machine)

Source: Internet
Author: User

I. About automated testing machine 1. What is an automated testing machine? Tools for batch testing of specified methods in the Class 2. What is the purpose of an automatic testing machine? A. this avoids lengthy test code. When there are many member methods in the class, the corresponding test code may be very long. Using testing can make the test code very concise. B. reduces the coupling between classes and test code, just in case, all methods in the class should be tested during testing. When we modify a method in the class, it is very likely that our test code will also be changed accordingly (for example, the method name and return value type are changed ), using the test function reduces the coupling between classes and test code, greatly reducing unnecessary workload. C. Added the flexibility of testing. The testing class and the class to be tested are often separated. When setting test parameters, you may need to check the specific method body (looking for boundary parameters), which is inconvenient. If you use a testing machine, the test parameters are declared in the corresponding method (Add corresponding annotations to the method), making it easy to modify parameters flexibly. 3. the principle of the tester can be implemented by annotation and reflection. The principle is very simple. I Thought That annotation is a type and I didn't want to use it in the past... the specific principle is: declare custom annotation Based on the parameter type of the method to be tested --> Add the corresponding annotation for the method --> write the test machine code using the reflection mechanism II. reference Materials such sharp things Of course not by me, predecessors in a long time before proposed, link: http://blog.csdn.net/rj042/article/details/6399965 P.S. we recommend that you read the link blog with this article. The original Article introduces a lot of related basic knowledge. This article is based on its practice 3. practice 1. the original article raised the question of Automatic Testing Machine: ------- requirements :( 1) define a single value annotation TestCase, so that it can be annotated with the method, and can be retained to the property type of annotation when the program is running is String, you must assign a value to the attribute in short form. (2) define a class MyClass. You must have parameters of the Methods Method1, 2, and 3, The return value type is 'string' type. The return value is the annotation in (1) to comment on Method1 and 3, and the attribute parameter value (3) defines a test class TestMyClass, reflection is required to test all methods annotated by TestCase in MyClass and the property value of the annotation is used as a parameter, call the corresponding method to return the test result ------- the above content is taken from the original article (directly sticking the question request ...) 2. the Code provided in the original article has almost no comments, and I don't know what the program has done after it is used up. Maybe the predecessors just want to demonstrate the process. Little cainiao said he didn't understand it, the source code is commented out in detail, in order to thoroughly understand its principle 3. on the code (annotations are already very detailed) [to be tested Methods class. java] 12345678910111213141516171819202122232425262728293031323334 // defines a class Methods, which requires three Methods: Method1, 2, 3 // The parameter and Return Value Type of the method are String Type, the returned value is the input parameter // use the custom annotation to annotate Method1, 3, assign a value to the attribute parameter: public class Methods {/*** @ param args */@ Annotation ("Param_1") // annotate Method1, indicates that the automatic test opportunity is interested in Method1 public String Method1 (String s) {// do something... like s + = "_ X"; return s;} // do not annotate Method2. The automatic testing machine filters out Method2 public String Method2 (String s) {// do something... like s + = "_ XX"; return s ;}@ Annotation ("Param3") // same as Method1 public String Method3 (String S) {// do something... like s + = "_ XXX"; return s ;}} [custom Annotation class Annotation. java] 1234567891011121314 import java. lang. annotation. *; // defines a single-value Annotation so that it can be annotated with the method, and can be retained to the property type of // Annotation when the program is running as String, the attribute value can be abbreviated as @ Target ({ElementType. METHOD}) // declare the object to which the annotation is applied. It can be multiple Type values @ Retention (RetentionPolicy. RUNTIME) // declare that the Annotation can be retained to the public @ interface Annotation {// the value defined here is both an attribute and a method, which is equivalent to "value ", key-value Pair String value (); // Annotation without a member is called a tag annotation // Annotation with only one member is called a single value annotation // Annotation with multiple members is called a multi-value annotation} [test class (Automatic Testing Machine) testAnnotation. java] 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 import java. lang. reflect. *; // defines a test class TestAnnotation. reflection is required to test all Methods annotated by Annotation in Methods. // The Annotation attribute value is used as a parameter, call the corresponding method to return the test result public class TestAnnotation {/** this is the so-called automatic testing machine * that uses the value given by the annotation as the parameter of the method to be tested, perform Batch tests on all methods in the specified class * avoiding lengthy test code ***/ @ SuppressWarnings ("rawtypes") public static void main (String [] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, invocationTargetException {// use the reflection mechanism to obtain the instance of the Class based on the Class name, which is different from the object of the general reference // Class (instance, reference ...) is the factory of A Common Object // That is to say, for A class A, the class Object of A is only one, while the common objects of A are a1, a2, a3... there can be many // new A () --> determine whether A Class object exists. If not, create it, if yes, continue --> Create a Common Object Class c = Class Based on the Class object. ForName ("Methods"); // obtain all the Methods declared in the Class Using Reflection [] MS = c. getDeclaredMethods (); System. out. println ("<automatic testing machine started...> \ n "); for (Method m: MS) {System. out. println ("start {"); String name = m. getName (); // determines whether the method has been annotated with the specified annotation if (m. isAnnotationPresent (Annotation. class) {System. out. println ("testing" + name + "method"); // obtain the Annotation object Annotation anno = m. getAnnotation (Annotation. class); // obtain the Annotation value, because Annotation is a single-value Annotation, and the value is Stri directly. Ng s = anno. value (); // obtain the Instance Object obj of the class = c. newInstance (); System. out. println ("input parameter" + s); // call the m method Object returnObj = m. invoke (obj, s); System. out. println ("Return Value:" + returnObj); System. out. println (name + "method tested");} else System. out. println (m. getName () + "method not annotated, the tester skips this method"); System. out. println ("} end \ n");} System. out. println ("<... the Automatic Testing Machine is disabled> ") ;}} 4. running result 123456789101112131415161718192021 <the automatic testing machine is started ...> Start {testing Method1 method passed in parameter Param_1 return value Param_1_XMethod1 method test completed} end start {Method2 method not annotated, tester skips this method} end start {testing Method3 method input parameter is Param3 return value is Param3_XXXMethod3 method test completed} end <... the Automatic Testing Machine is disabled> 4. in the summary example program, we only need to test specific methods of specific classes to illustrate the principle of the testing machine, but do not worry. Reflection mechanism is hailed as one of the most exciting aspects of Java, and it is definitely not a blow. The reflection mechanism allows the child class to obtain the parent class and expand it to get a clear class hierarchy. It is also easy to test multiple classes. We only need to create an array of class names, loop, and so on. Of course, the use of [reflection + annotation] for automatic testing also has the advantage of testing a family member, father, grandfather... this is simply beyond the imagination of the test code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.