Junit unit test and reflection

Keywords: Java calculator Junit

1.Junit unit test

Test classification:
1. Black box test: do not need to write code, do not see the process of program execution, input some parameters, and see the expected results.
2. White box test: you need to write code, you can see the process of program execution, enter some parameters, and see the expected results.
Junit use: white box test
Let's start with an example:

package com.wcy.demo1.Junit;

/*
    Calculator class
 */
public class Calculator {
    /**
     * addition
     * @param a
     * @param b
     * @return
     */
    public int add(int a,int b){
        return a+b;
    }

    /**
     * subtraction
     * @param a
     * @param b
     * @return
     */
    public int sub(int a,int b){
        return a-b;
    }
}

package com.wcy.demo1.Junit;

public class demoJunit {
    public static void main(String[] args) {
        //create object
        Calculator c=new Calculator();
        int result1 = c.add(1, 2);
        System.out.println(result1);

        int result2 = c.sub(5, 1);
        System.out.println(result2);

    }
}

The above method is cumbersome and inconvenient
A class can only write one main method. Unit testing will solve this problem.

Step:
1. Define a test class (test case)
Suggestions:
Test class name: test class name
Package name: xxx.xxx.xx.Test
2. Define test method: can run independently
Suggestions:
Method name: method of Test name
Return value: void
Parameter list: empty parameter
3. Annotate the method
4. Import Junit dependency

package test;

import com.wcy.demo1.Junit.Calculator;

public class CalculatorTest {
    /**
     * Test the add method
     */
    @Test
    public void testAdd(){
        //System.out.println("I was executed");
        Calculator calculator=new Calculator();
        int result = calculator.add(1, 2);
        //System.out.println(result);
        //Assert, I assert that the result is 3
        Assert.assertEquals(3,result);
    }
}

Judgment result: red represents failure, green represents success. Generally, we will use assertion operation to process the result. Assert.assertEquals(3,result);

5. Initialization method, which is used for resource application. All test methods will execute the method Before execution, adding @ Before to the method
6. Release resource method. After all test methods are executed, the method will be executed automatically. Add @ after before the method

2. Reflection: the soul of frame design

2.1 basic overview of reflection

Framework: semi-finished software. It can develop software on the basis of framework and simplify coding.
Concept (abstraction): encapsulate the various components of a class as other objects, which is the reflector
System.

Benefits:
1. These objects can be operated during program running.
2. It can decouple and improve the scalability of the program.

From the previous figure, we can see that the Class object phase has three functions
1. Get member variables
2. Get the construction method
3. Get member method
Let's use the code to introduce them.

2.2 reflection: get member variables

1. First, we create a Person class

package reflect;

public class Person {
    private  int age;
    private String name;

    public String a;
    protected String b;
    String c;
    private String d;

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", a='" + a + '\'' +
                ", b='" + b + '\'' +
                ", c='" + c + '\'' +
                ", d='" + d + '\'' +
                '}';
    }
    
    public Person(){

    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }
}

2. After creation, we can get the Class object through reflection

Field [] getfields(): get all public decorated member variables
Field getField(String name): gets the public decorated member variable of the specified name
Field[] getDeclaredFields(): get all member variables without considering modifiers
Field getDeclaredField(String name)
Note: d.setAccessible(true); / / violent reflection

package reflect;

import java.lang.reflect.Field;

public class ReflectDemo1 {
    public static void main(String[] args) throws Exception {
        //1. Get the Class object of Person
        Class personClass = Person.class;
        //2. Get member variables
        /*
            Field[] getFields():Get all public decorated member variables
            Field getField(String name):Gets the public decorated member variable of the specified name
         */

        Field[] fields = personClass.getFields();
        for (Field field : fields) {
            System.out.println(field);//public java.lang.String reflect.Person.a
        }

        System.out.println("===========================");
        Field a = personClass.getField("a");
        //Get the value of member variable a
        Person p=new Person();
        Object value = a.get(p);
        System.out.println(value);//null
        //Set the value of a
        a.set(p,"Zhang San");
        System.out.println(p);//Person{age=0, name='null', a='Zhang San', b='null', c='null', d='null'}

        System.out.println("============================");

        //Field[] getDeclaredFields():Get all member variables, regardless of modifiers
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
            /*Output results
            private int reflect.Person.age
            private java.lang.String reflect.Person.name
            public java.lang.String reflect.Person.a
            protected java.lang.String reflect.Person.b
            java.lang.String reflect.Person.c
            private java.lang.String reflect.Person.d
            */

        }
        System.out.println("============================");


        //Field getDeclaredField(String name)
        Field d = personClass.getDeclaredField("d");
        //Ignore security check for access modifier
        d.setAccessible(true);//Violent reflex
        Object value2 = d.get(p);
        System.out.println(value2);
    }
}

2.3 reflection: obtain the construction method

1. First, create the Person class

package reflect;

public class Person {
    private String name;
    private  int age;


    public String a;
    protected String b;
    String c;
    private String d;
    public Person(){

    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", a='" + a + '\'' +
                ", b='" + b + '\'' +
                ", c='" + c + '\'' +
                ", d='" + d + '\'' +
                '}';
    }

    public Person(String name,int age) {
        this.name = name;
        this.age = age;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }
}

2. Second, reuse

package reflect;

import java.lang.reflect.Constructor;

public class ReflectDemo2 {
    public static void main(String[] args) throws Exception {
        //1. Get the Class object of Person
        Class personClass = Person.class;
        //2. Get the construction method
        /*
            Constructor<?>[] getConstructors()
         */
        //Constructor<?>[] getConstructors()
        Constructor constructor = personClass.getConstructor(String.class,int.class);
        System.out.println(constructor);//public reflect.Person(java.lang.String,int)
        //create object
        Object person = constructor.newInstance("Zhang San", 23);
        System.out.println(person);//Person{age=23, name='Zhang San', a='null', b='null', c='null', d='null'}

        System.out.println("========================");
        Constructor constructor1 = personClass.getConstructor();
        System.out.println(constructor1);//public reflect.Person()
        //create object
        Object person1 = constructor1.newInstance();
        System.out.println(person1);//Person{age=0, name='null', a='null', b='null', c='null', d='null'}

        Object o = personClass.newInstance();
        System.out.println(o);//Person{age=0, name='null', a='null', b='null', c='null', d='null'}

    }
}

Create object:
1.T newInstance(Object...initargs)
2. If the null parameter construction method is used to create an object, the operation can be simplified: newInstance method of Class object

2.4 reflection: get member method

1. First, create the Person class

package reflect;

public class Person {
    private String name;
    private  int age;


    public String a;
    protected String b;
    String c;
    private String d;
    public Person(){

    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", a='" + a + '\'' +
                ", b='" + b + '\'' +
                ", c='" + c + '\'' +
                ", d='" + d + '\'' +
                '}';
    }

    public Person(String name,int age) {
        this.name = name;
        this.age = age;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void eat(){
        System.out.println("Eat, eat, eat.......");
    }

    public void eat(String food){
        System.out.println("Eat, eat, eat......."+food);
    }
}

2. Use

package reflect;

import java.lang.reflect.Method;

public class ReflectDemo3 {
    public static void main(String[] args) throws Exception {
        //1. Get the Class object of Person
        Class personClass = Person.class;
        //2. Get member method
        //Gets the method of the specified name
        Method eat_method = personClass.getMethod("eat");
        Person p=new Person();
        //Execution method
        eat_method.invoke(p);//Eat, eat, eat.......

        Method eat_method2 = personClass.getMethod("eat", String.class);
        //Execution method
        eat_method2.invoke(p,"Fart");

        System.out.println("=====================");
        //Method to get all public modifiers
        Method[] methods = personClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
            String name = method.getName();
            System.out.println(name);
        }
    }
}

Get method:
Execution method: Object invoke (Object obj, Object args)
Get method name: String getName: get method name

2.5 reflection: get class name

As before:

//Get class name
        String ClassName = personClass.getName();
        System.out.println(ClassName);//reflect.Person

Posted by rolwong on Sat, 27 Jun 2020 00:05:30 -0700