Java Advanced Junit Unit Testing, Reflection, Annotation

Keywords: Java unit testing

;

Catalog

Junit Unit Test

reflex

The principle of reflection:

Methods for getting Class objects (three different stages, three different methods)

 Getting Method of Class Object

Field class (member variable)

Constructor class (constructor)

Method class (member method)

annotation

JDK predefined annotations

Custom Notes

Junit Unit Test

 Test Classification:
        1. Black box test: No code is required, give the input value to see if the program can output the expected value.
        2. White box test: need to write code.Focus on the specific execution process of the program.

Junit unit test is a white box test

Test steps:

  1. Define a test class
  2. Define a test method    Return value void   No reference
  3. Annotate @Test and import dependencies

Decision Result

Red is failure, green is success

Generally, assertions are used to process results

  • Assert.assertEquals (expected result, result of operation);

Supplementary Notes

  • @Before: Modified methods are automatically executed before test methods
  • @After: Modified methods are automatically executed after test method execution

Sample Code

​
public class t1 {
    @Test
    public void t_1(){
        System.out.println("Test Class");
    }
    @Test
    public void t_2(){
        int r=1+1;
        Assert.assertEquals(2,r);//Using an assertion expects a result of 2
    }

    @Before
    public void before(){
        System.out.println("Initialization operation");
    }

    @After
    public void close(){
        System.out.println("Release Resources");
    }

}

​

reflex

Reflection mechanism: encapsulate components of a class as other objects

Benefits:

  •   You can manipulate these objects while the program is running. (Dynamic Compilation)
  •    It can decouple and improve the scalability of the program.
  •    Access to private properties    

The principle of reflection:

Analysis:

The java file is compiled to generate a class file, which contains member properties, member methods, construction methods, and so on.Class files load Class objects into memory through the class loader;Create Objects from Class Objects

Methods for getting Class objects (three different stages, three different methods)

  •  Class.forName("full class name"): Loads a byte code file into memory and returns a Class object         (Most used in configuration files, the class name is defined in the configuration file.Read files, load classes)
  •  Class name.class: Obtained by the class attribute of the class name       ( Used mostly for parameter transfer)
  •  Object.getClass():The getClass() method is defined in the Object class. (How to get byte codes for objects)

            Note: The same byte code file (*.class) will only be loaded once during a program run, regardless of which way the lass objects are obtained.
Sample Code

public void t1() throws ClassNotFoundException {
        Class<?> aClass = Class.forName("Exercise Pack 4.t4.person");//Get Class Object by Fully Qualified Name
        Class<person> personClass = person.class;//Get Class Object by Class Name
        Class<? extends person> aClass1 = new person().getClass();//Getting Class Objects from Objects
        System.out.println(aClass==personClass);//true
        System.out.println(aClass==aClass1);//true

    }

 Getting Method of Class Object

 Get member variables

  • Field[] getFields(): Gets all public-modified member variables
  • Field getField(String name)  Gets the public-modified member variable with the specified name
  • Field[] getDeclaredFields() Members get all quantities regardless of modifiers
  • Field getDeclaredField(String name)     Gets the member variable with the specified name 

   Get construction methods

  •  Constructor<?>[]GetConstructors()         Returns the constructor for the specified parameter type public
  •  Constructor <T> getConstructor (class <?>...ParameterTypes)  Gets the specified public constructor
  • Constructor <T> getDeclaredConstructor (class <?>...ParameterTypes)   Gets the specified constructor
  • Constructor<?>[]GetDeclaredConstructors()  Returns the private and public constructors of the specified parameter type

Get Members Method

  • Method[] getMethods()  Return all public methods
  • Method getMethod(String name, class <?>...ParameterTypes)  Gets the specified public method
  • Method[] getDeclaredMethods()   Return all methods
  • Method getDeclaredMethod(String name, class <?>...ParameterTypes)  Get the specified method

Field class (member variable)

  • void set(Object obj, Object value)  : Set Value
  • get(Object obj): Get a value

Constructor class (constructor)

  • T newInstance(Object... initargs)  : create object

If an object is created using an empty parameter construction method, the operation can be simplified:newInstance method for Class objects

Method class (member method)

  • Object invoke(Object obj, Object... args): Execute method

Sample Code

 public void t2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Class<person> personClass = person.class;//Get Class Loader
        Constructor<person> constructor = personClass.getConstructor(String.class);//Get a constructor with one parameter
        person person = constructor.newInstance("Zhang San");//Establish Objects
        Field[] fields = personClass.getFields();//Getting public attribute variables
        Stream.of(fields).forEach(System.out::println);//Public attributes: namep, agep
        Field[] declaredFields = personClass.getDeclaredFields();//Get all attribute variables
        Stream.of(declaredFields).forEach(System.out::println);//name,age,namep,agep
        System.out.println("==========================");
        Field name = personClass.getDeclaredField("name");
        name.setAccessible(true);//Violent Reflex
        System.out.println(name.get(person));//Zhang San
        System.out.println("===========================");
        Method[] methods = personClass.getMethods();//Get all public methods
        Stream.of(methods).forEach(System.out::println);
        Method method = personClass.getMethod("show");//Get the specified method
        method.invoke(person);//Execution Method
    }
public class person {
    private String name;
    private int age;
    public String namep;
    public int agep;

    public void show(){
        System.out.println("Execution Method");
    }
...
}

 Case: Make a framework: you can create any class and execute any method

 public void t3() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Properties properties = new Properties();
        ClassLoader classLoader = test.class.getClassLoader();//Get the loader for this class
        InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties");//Get Input Stream
        properties.load(resourceAsStream);
        String classname = properties.getProperty("classname");//Get data from a file
        String mothodname = properties.getProperty("mothodname");
        Class<?> aClass = Class.forName(classname);//Get Class Loader
        Object o = aClass.newInstance();//Call parameterless construction to create object
        Method method = aClass.getMethod(mothodname);//Get the specified method
        method.invoke(o);//Execution Method
    }

 Definition in configuration file: fully qualified name and method name of class

annotation

Annotations are a new feature after JDK1.5 to describe programs
Use the format of the note: @Note name

Classification of actions:

  • Document writing: Generate a document from the comments identified in the code [Generate a document doc document]
  • Code Analysis: Code is analyzed by comments identified in the code [using reflection]
  • Compilation Checks: Annotations identified in the code allow the compiler to perform basic compilation checks [Override]

JDK predefined annotations

  • @Override    : Detects if the method labeled by this annotation inherits from the parent class (interface)
  • @Deprecated: The contents of this annotation indicate obsolete
  • @SuppressWarnings: Suppression warning parameters typically pass "all" and place it on a class

Custom Notes

Format:

meta annotation

public @interface annotation name {
                Attribute list;
            }

Annotations are essentially an interface that inherits from the Annotation interface

        For example: public interface MyAnno extends java.lang.annotation.Annotation {}

Attribute method:

        Return value: basic data type, String, enumeration, annotation, array of the above types

        A list of attributes is defined and must be assigned when using annotations

 Meta-annotations (use the first two when customizing annotations)

  • @Target: Describes where notes can work

                ElementType value:

                        TYPE: Can act on classes

                        METHOD: Can act on Methods

                        FIELD: Can act on member variables

  • @Retention: Describes the stage at which notes are retained   Parameter uses RetentionPolicy.RUNTIME
  • @Documented: Describes whether the comment was extracted into an api document
  • @Inherited: Describes whether annotations are inherited by subclasses

Parse notes,

  • 1. Object to get the position defined by the annotation (Class, Method,Field)
  • 2. Get the specified comment
  • 3. Get data from notes

Sample Code

//Custom Notes
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {
    String classname();
    String mothodname();
}
//Use annotations on classes
@Pro(classname = "test.t1.person",mothodname = "show")
//Parsing data in annotations
 public void t4() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NullPointerException, ClassNotFoundException {
        Class<test> testClass = test.class;//Gets the location object defined by the annotation
        Pro annotation = testClass.getAnnotation(Pro.class);//Gets the specified annotation object
        Class<?> personClass = Class.forName(annotation.classname());//Getting data from annotations
        Object person = personClass.newInstance();
        personClass.getMethod(annotation.mothodname()).invoke(person);
    }

 Pro annotation = testClass.getAnnotation(Pro.class);Is equivalent to getting one Implementation class object for Pro interface

 public class ProImpl implements Pro{
                        public String classname(){
                            return "test.t1.person";
                        }
                        public String mothodname(){
                            return "show";
                        }
                    }

  

 

Posted by BuzzLY on Thu, 02 Sep 2021 12:15:13 -0700