Unit testing and annotation learning of Java Foundation

Posted by godster on Fri, 12 Nov 2021 11:57:52 +0100

Junit unit test

Test classification:

  • Black box test: you don't need to write code. Give the input value to see if the program can output the expected value.
  • White box test: you need to write code. Pay attention to the specific execution process of the program.

What is unit testing

  • Test part of the code

  Add end teachers to get more programming materials for free

Junit introduction

Junit is a unit testing framework of Java language. It belongs to white box testing. It is simply understood as the main method that can be used to replace Java. Junit is a third-party tool and needs to be used after importing the jar package.

What is Junit:

  • Is a unit test framework written by a third party, which can replace the main method
  • Junit needs to import jar packages and compressed packages, which contain a lot of java code. Because Junit is widely used, idea already includes Junit, so you only need to import it

Junit benefits:

  • You can test part of the code separately

Steps to use Junit:

>   Writing test classes
>
>   Write test method:
>
>      Must be a public modifier
>
>      Must be a void with no return value
>
>      There must be no parameters
>
>      > Public void method name (){
>      >             Test code
>     >          }
>
>      Add @ Test annotation to Test method
>
>      Run test method
>
>      Look at the results
>
>        Green: indicates passing
>        Red: indicates failure

Use of Junit

  • Write a test class and simply understand that Junit can be used to replace the main method of java
  • Add the annotation home. PHP? Mod = Space & uid = 101628 on the test class method
  • @Requirements for the method modified by test: public void method name () {...}. The method name starts with test and has no parameters.
  • Add the Junit library to the lib folder, and then associate the jar package
  • Usage: click the green arrow on the left of the method to execute the current method (the method must be marked @ Test). Execution result Red: indicates failure; execution result green: indicates success
 Copy code behind code
package com.mobai;

import org.junit.Test;
import java.util.Arrays;
/**
 * Software: IntelliJ IDEA 2020.1 x64
 * Author: MoBai·Jay
 * ClassName:Test
 * Class description: Junit test
 */
public class TestDemo1 {

    @Test
    public void test01() {
        for (int i = 0; i < 100; i++) {
            System.out.println(" i: " + Arrays.class.getClass());
        }
    }
}

Common notes

  • @Test, used to decorate the test method to be executed
  • @Before, the decorated method will be automatically executed before the test method
  • @After, the modified method will be automatically executed after the test method is executed
 Copy code behind code
package com.mobai;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
/**
 * Software: IntelliJ IDEA 2020.1 x64
 * Author: MoBai·Jay
 * ClassName:Test
 * Class description: Junit test
 */
public class TestDemo1 {

    @Before
    public void testBefore() {
        System.out.println(" Pre method ");
    }

    @After
    public void testAfter() {
        System.out.println(" Post method ");
    }

    @Test
    public void test01() {
        for (int i = 0; i < 10; i++) {
            System.out.println(" i: " + Arrays.class.getClass());
        }
    }
}

Class object

  • When the program needs to use the Person class, the Person.class will be loaded into memory
  • Load Person.class into memory and store member variables, member methods and construction methods respectively
  • The Java virtual opportunity actively creates a class object to describe the content of Person.class in the method area

The concept of reflection

>What is reflection?

  • In the process of program running, get the Class construction methods, member methods and member variables through the Class object, and operate them

>Application scenario of reflection

  • Intelligent tips of development tools such as idea
  • Development framework SSM

>Benefits of reflection

  • You can manipulate these objects while the program is running.
  • It can decouple and improve the scalability of the program.

Three methods to obtain Class object information

How to get the CLASS objecteffectApplication scenario
Class name.classGet through the class attribute of the class nameMostly used to pass parameters
Class.forName("class full name")Obtained by the specified string pathIt is used to load configuration files, define class names in configuration files, read files, and load classes
Object. getClass()Obtained through the getClass() method of the objectThe bytecode used to obtain the object

Three ways to get Class objects

  • Class name.class
  • Object name (. getClass())
  • Class. Forname (full class name) / (full class name: package name. Class name)

>Note: all three methods get the same object

 Copy code behind code
/**
 * Software: IntelliJ IDEA 2020.1 x64
 * Author: MoBai·Jay
 * ClassName:TestClass
 * Class description: three ways to obtain class objects
 */
public class TestClass {
    public static void main(String[] args) throws Exception {
        // 1. Class name.class
        Class clz = Book.class;
        System.out.println("clz = " + clz);

        // 2. Pass the object name. getClass()
        Book book = new Book();
        Class clz2 = book.getClass();
        System.out.println("clz2 = " + clz2);

        // 3. Pass class. Forname
        Class clz3 = Class.forName("com.mobai.annion.Book");
        System.out.println("clz3 = " + clz3);

        // All three methods get the same object
        System.out.println(clz2 == clz3);
        System.out.println(clz == clz2);
    }
}

  Add end teachers to get more programming materials for free

Get Class object information

Common methods:

String getSimpleName();Get the simple class name, just the class name, no package
String getName();Obtain the complete class name, including package name + class name
T newTnstatance();The Class represented by this Class object is a new instance < br / > requirement: the Class must have a < public > parameterless constructor
 Copy code behind code
public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException {
        // 1. Get Class object
        Class clazz = Class.forName("com.mobai.annion.Book");

        // 2. Call method getName
        String name1 = clazz.getName();
        // name1 = com.mobai.annion.Book
        System.out.println("name1 = " + name1);

        // 2.1 calling method getSimpleName
        String name2 = clazz.getSimpleName();
        // name2 = Book
        System.out.println("name2 = " + name2);
    }
}

Construction method of public obtained by reflection

Constructor class functions:

  • Represents a constructor in a class

How to get the public Constructor object:

  • Get Class object
  • Get construction method through Class object

>CLS. Getconstructor(); get a public constructor
>
>CLS. Getconstructors(); get the construction methods of all public

  • Methods of Constructor class:

    • newInstance(); create object
  • Class object of basic data type and reference data type

    > int.class != Integer.class

  • Create a student class
 Copy code behind code
/**
 * Software: IntelliJ IDEA 2020.1 x64
 * Author: MoBai·Jay
 * ClassName:Student
 * Class description: student class
 */
public class Student {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student(String name) {
        this.name = name;
    }

    public Student(Integer age) {
        this.age = age;
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  • Test class
 Copy code behind code
public class TestDemo1 {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("com.mobai.fanshe.Student");
        // 1. Get the construction methods of all public
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println("constructor = " + constructor);
        }

        // 2. Get a public constructor
        Constructor<?> constructors1 = clazz.getConstructor();
        // public com.mobai.fanshe.Student()
        System.out.println("constructors1 = " + constructors1);

        // 2.1 reflection acquisition specifies the construction method
        Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
        // public com.mobai.fanshe.Student(java.lang.String,java.lang.Integer)
        System.out.println("constructor = " + constructor);
    }
}

Reflection creates objects through the Constructor

 Copy code behind code
public class TestDemo1 {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("com.mobai.fanshe.Student");
        // 1. Get the construction methods of all public
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println("constructor = " + constructor);
        }

        // 2. Get a public constructor
        Constructor<?> constructors1 = clazz.getConstructor();
        // public com.mobai.fanshe.Student()
        System.out.println("constructors1 = " + constructors1);

        // 2.1 reflection acquisition specifies the construction method
        Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
        // public com.mobai.fanshe.Student(java.lang.String,java.lang.Integer)
        System.out.println("constructor = " + constructor);

        // 3. Create an object using newInstance
        Object instance = constructor.newInstance("Mo Baijun", 15);
        // Student{name = 'Mo Baijun', age=15}
        System.out.println("instance = " + instance);
    }
}

Reflection gets the constructor of the declaration

The declared Constructor is the Constructor in the class, regardless of permission

How to get the declared Constructor:

  • Get Class object
  • Get the declared Constructor through the Class object

>The rule of declared:
>
>   cls.getConstructor();    Get a public constructor
>   cls.getConstructors();    Get the constructor of all public
>   CLS. Getdeclaraedconstructors(); get all declared constructors
>   CLS. Getdeclaraedconstructor(); get a declared constructor
>   No Declared is public
>   Declared is declared
>   No s is to get one
>   s is to get multiple

We call the private construction method before we use it.

  • con.setAccessible(true); violent reflection
  • Student class
 Copy code behind code
public class Student {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student(String name) {
        this.name = name;
    }

    private Student(Integer age) {
        this.age = age;
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  • Test class
 Copy code behind code
public class TestDemo2 {
    public static void main(String[] args) throws Exception {
        // 1. Get Class object
        Class<?> clazz = Class.forName("com.mobai.fanshe.Student");

        // 2. Get the construction method of a declaration
        Constructor<?> constructor = clazz.getDeclaredConstructor(Integer.class);
        // private com.mobai.fanshe.Student(java.lang.Integer)
        System.out.println("constructor = " + constructor);

        // Violent reflex
        constructor.setAccessible(true);
        // create object
        Object instance = constructor.newInstance(16);
        System.out.println("instance = " + instance);
    }
}

Class creates an object using the newInstance method

Class's newInstance method is to create an object using a parameterless construct

 Copy code behind code
public class TestDemo3 {
    public static void main(String[] args) throws Exception {
        // Get Class object
        Class<?> clazz = Class.forName("com.mobai.fanshe.Student");
        // Get parameterless construction
        Constructor<?> constructor = clazz.getConstructor();
        // Creating objects through parameterless construction
        Object instance = constructor.newInstance();
        // instance = Student{name='null', age=null}
        System.out.println("instance = " + instance);

        // Class object method for creating objects
        Student instance1 = (Student) clazz.newInstance();
        // instance1 = Student{name='null', age=null}
        System.out.println("instance1 = " + instance1);
    }
}

Reflection acquisition Method

  • Method class function

    • Represents a method in a class
  • How to get the Method object

    • Get Class object
    • Get Method through Class object
    • cls.getMethods(); get all public methods
    • cls.getMethod(); get a public method
    • CLS. Getdeclaraedmethods(); get all declared methods
    • CLS. Getdeclaraedmethod(); get a declared method
  • Method in method class: this method can be called when the method is obtained

    • Object invoke(Object target, Object... args);
    • Object target: the object that calls the method
    • Object... args: parameters passed when calling the method
    • Object: return value type
  • Student class
 Copy code behind code
public class Student {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student(String name) {
        this.name = name;
    }

    private Student(Integer age) {
        this.age = age;
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  • Get all methods through class
 Copy code behind code
public class TestDemo4 {
    public static void main(String[] args) throws Exception {
        // Get Class object
        Class<?> clazz = Class.forName("com.mobai.fanshe.Student");
        // Get methods through CLass
        Method[] methods = clazz.getMethods();
        // Traversal to get all public methods
        for (Method method : methods) {
            System.out.println("method = " + method);
        }

        // Get a method
        Method setName = clazz.getMethod("setName", String.class);
        // setName = public void com.mobai.fanshe.Student.setName(java.lang.String)
        System.out.println("setName = " + setName);

        // Gets all declared methods
        Method[] methods1 = clazz.getDeclaredMethods();
        for (Method method : methods1) {
            System.out.println("method = " + method);
        }
        // Gets a declared method
        Method getName = clazz.getDeclaredMethod("getName");
        // public java.lang.String com.mobai.fanshe.Student.getName()
        System.out.println("getName = " + getName);
    }
}

  Add end teachers to get more programming materials for free

What is annotation?

>   Annotation, also known as metadata. A code level description. It is a feature introduced in JDK1.5 and later versions. It is at the same level as class, interface and enumeration. It can be declared in front of packages, classes, fields, methods, local variables, method parameters, etc. to describe and annotate these elements.

  • Function of annotation:

    • Explain the program to the computer
    • Can be read by other programs
  • Format of annotation

    • The annotation exists in the code with "@ annotation name", and some parameters can be added
  • Where is annotation used?

    • It can be attached to package,class,method,field, etc., which is equivalent to adding additional auxiliary information to them. These metadata can be accessed through reflection mechanism programming
  • Function classification:

    • Writing documents: generate documents through the annotations identified in the code [generate doc documents]
    • Code analysis: analyze the code through the annotation marked in the code [use reflection]
    • Compilation check: enable the compiler to implement basic compilation check through the annotations identified in the code [Override]
  • Common notes:

    • @Author: used to identify the author's name. The default of eclipse development tools is the system user name.
    • @since:    From which version
    • @Version: used to identify the version number of an object. Scope of application: file, class and method.
    • @Override: used to modify the method declaration and tell the compiler that the method overrides the method in the parent class. If the method does not exist in the parent class, the compilation fails.

Custom annotation

Custom Annotation: Annotation is essentially an interface, which inherits the Annotation interface by default

 Copy code behind code
public interface MyAnno extends java.lang.annotation.Annotation {}
  • Custom annotation
 Copy code behind code
// Empty annotation
public @interface Anno01 {
}
  • Annotation with parameters

Only the basic data types provided by Java can be used. String can be used, Class can be used, enumeration Class can be used, others have not been tested yet, wrapper Class cannot be used, and custom Class cannot be used

 Copy code behind code
public @interface Anno02 {
    // attribute
    String name();
    double price() default 99;
    String[] authors();

//     Anno01 abc(); //  annotation
//    WeekDay w();
//    Class p();
}

enum WeekDay {
    SUN, MON
}

class Person {

}

Attribute type of annotation

  • Eight basic data types
  • String, annotation, enumeration, Class
  • One dimensional array of the above types

>Custom class is not allowed

Use custom annotations

  • Annotations can be used to save data

  • Use custom annotation format:

    >@ annotation name (attribute name = attribute value, attribute name = attribute value)

Note: the attribute of the annotation can have a default value. When the annotation is used, the default value is used without assignment, and the assignment is based on the assigned value

  • Define annotation
 Copy code behind code
package com.mobai.annaction;

// Custom annotation
public @interface MoBai {
    // name
    String name();

    // Default properties
    String value() default "Frame Division";
}
  • Using annotations
 Copy code behind code
public class AnnactionTest {

    @MoBai(name = "Ink white",value = "")
    public static void main(String[] args) {
    }

    @Test
    public void annTest(){
    }
}

Special case of custom annotation

When the annotation has only one attribute and the attribute name is value, the attribute name can be omitted when using the annotation

  • Custom annotation
 Copy code behind code
public @interface MoBai {
    String value();
}
  • Using annotations
 Copy code behind code
@MoBai("abc")
public class Demo11 {
    @MoBai(value = "abc")
    public static void main(String[] args) {
    }
}

Meta annotation

  • @Target
  • @Retention

>   Annotations that modify annotations are called meta annotations

@Target meta annotation:

  • By default, annotations can be placed anywhere

    >   Limit where annotations can be placed
    >     @ Target(ElementType.TYPE)             Annotations can only be placed on classes or interfaces
    >     @ Target(ElementType.CONSTRUCTOR)     Annotations can only be placed on construction methods
    >     @ Target(ElementType.FIELD)           Annotations can only be placed on member variables
    >     @ Target(ElementType.METHOD)           Annotations can only be placed on member methods
    >     @ The Target(ElementType.LOCAL_VARIABLE) annotation can only be placed on local variables

@Retention meta note:

  • The default is the CLASS phase

>   Limit when annotations can live
>
>   > SOURCE = = = = = = = = = = >>CLASS = = = = = = = = = = = = = >>RUNTIME
>    > *  Source code phase (. Java) = = > > compile = = > >. Class = = > > run

  • Custom annotation
 Copy code behind code
//@Target(ElementType.TYPE) / / annotations can only be placed on classes or interfaces
//@Target(ElementType.CONSTRUCTOR) / / annotation can only be placed on constructor
//@Target(ElementType.FIELD) / / annotation can only be placed on member variables
//@Target(ElementType.METHOD) / / annotations can only be placed on member methods
//@Target(ElementType.LOCAL_VARIABLE) / / annotations can only be placed on local variables
@Retention(RetentionPolicy.RUNTIME)
public @interface MoBai {
}
  • Using annotations
 Copy code behind code
@MoBai
public class Demo12 {
    @MoBai
    private String a;

    @MoBai
    public Demo12() {

    }

    @MoBai
    public static void main(String[] args) {
        @MoBai
        int x = 10;
    }
}

Annotation parsing

  • What is annotation parsing?

>   Get the data saved in the annotation

  • Annotation resolution related interfaces?

>   AnnotatedElement interface:
>
>      Annotation getannotation (class < T > annotationclass) gets an annotation
>
>      Annotation[] getAnnotations()    Get multiple annotations
>
>      Boolean isannotationpresent (class <? Extends annotation > annotationclass) determines whether there is a specified annotation
>
>      >  Note: Constructor, Field and Method implement the AnnotatedElement interface

  • How to parse annotations?

>   The annotation is obtained by whoever has the annotation
>   Annotation on the construction method, the Constructor object is used to obtain the annotation
>   Annotation on the member Method, use the Method object to obtain the annotation
>   Annotation on the member variable, use the Field object to get the annotation
> *   Use reflection

  • Create custom annotation
 Copy code behind code
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Software: IntelliJ IDEA 2020.1 x64
 * Author: MoBai·Jay
 * [@]Interface:MoBook
 * Annotation Description: Custom annotation
 */
// Limited method use
@Target(ElementType.METHOD)
// Live to run time
@Retention(RetentionPolicy.RUNTIME)
public @interface MoBook {
    String name();

    double price();

    String[] authors();
}
  • Defining data class usage annotations
 Copy code behind code
/**
 * Software: IntelliJ IDEA 2020.1 x64
 * Author: MoBai·Jay
 * ClassName:Book
 * Class description: Book Class
 */
public class Book {
    @MoBook(name = "Frame Division", price = 25.0, authors = "Ink white")
    public void sell() {

    }
}
  • Test class
 Copy code behind code
public class TestMoBook {
    public static void main(String[] args) throws Exception {
        // 1. Get Class object
        Class<?> className = Class.forName("com.mobai.annion.Book");
        // 2. Get Method object
        Method method = className.getMethod("sell");
        // 3. Get annotation through method object
        Annotation[] annotations = method.getAnnotations();
        // 4. Traversal array
        for (Annotation annotation : annotations) {
            System.out.println("annotation = " + annotation);
        }
        // 3.3 boolean isAnnotationPresent​(Class<? extends Annotation> annotationClass)
        //   Determine whether there is a specified annotation
        boolean b = method.isAnnotationPresent(MoBook.class);
        System.out.println(b);
        if (b) {
            // 3.2 Annotation getAnnotation (class < T > annotationclass) gets an annotation
            MoBook ann = method.getAnnotation(MoBook.class);
            System.out.println(ann.name() + "::" + ann.price() + "::" + Arrays.toString(ann.authors()));
        }
    }
}

   Add end teachers to get more programming materials for free

Topics: UE4