系列文章目录
JavaSE基础的单元测试和反射相关内容的学习
文章目录
- 系列文章目录
- 前言
- 一、单元测试
- 1.单元测试概述
- 2.单元测试快速入门
- 3.单元测试常用注解
- 二、反射
- 1.反射概述
- 2.反射获取类对象
- 3.反射获取构造器对象
- 4.反射获取成员变量对象
- 5.反射获取方法对象
- 6.反射的作用—泛型擦除
- 7.反射的作用—通用框架的底层原理
- 总结
前言
一、单元测试
1.单元测试概述
2.单元测试快速入门
package org.example.junit;public class UserService {public String loginName(String loginName,String password){if ("admin".equals(loginName)&&"123".equals(password)){return "登录成功";}else {return "登录失败";}}public void selectName(){System.out.println(10/0);System.out.println("查询用户成功");}
}
package org.example.junit;import org.junit.Assert;
import org.junit.Test;/*** 测试类*/
public class TestUserService {/*** 测试方法必须无参且无返回值*/@Testpublic void testLoginName(){UserService userService=new UserService();String rs = userService.loginName("admin", "123");//进行预期结果的正确性测试: 断言Assert.assertEquals("您的功能出现问题","登录成功",rs);}@Testpublic void testUserSelect(){UserService userService=new UserService();userService.selectName();}
}
3.单元测试常用注解
package org.example.junit;import org.junit.*;/*** 测试类*/
public class TestUserService {//修饰实例方法@Beforepublic void before(){System.out.println("=============before方法执行========");}@Afterpublic void after(){System.out.println("===============after方法执行============");}//修饰静态方法@BeforeClasspublic static void beforeClass(){System.out.println("============beforeClass方法执行==============");}@AfterClasspublic static void afterClass(){System.out.println("===============afterClass方法执行=============");}/*** 测试方法必须无参且无返回值*/@Testpublic void testLoginName(){UserService userService=new UserService();String rs = userService.loginName("admin", "123");//进行预期结果的正确性测试: 断言Assert.assertEquals("您的功能出现问题","登录成功",rs);}@Testpublic void testUserSelect(){UserService userService=new UserService();userService.selectName();}
}
二、反射
1.反射概述
2.反射获取类对象
package org.example.reflect_class;/*** 目标:反射第一步:获取class类对象*/
public class Test {public static void main(String[] args) throws Exception {//1.class类中的一个静态方法:forNameClass c=Class.forName("org.example.reflect_class.Student");System.out.println(c);//2.类名.classClass c1=Student.class;System.out.println(c1);//3.对象.getClass() 获取对象对应的类的class类对象Student s=new Student();Class c2=s.getClass();System.out.println(c2);}
}
3.反射获取构造器对象
使用反射获取构造器对象并创建对象
package org.example.reflect_constructer;public class Student {private String name;private int age;public Student() {System.out.println("无参构造器执行");}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}public Student(String name, int age) {System.out.println("有参构造器执行");this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
package org.example.reflect_constructer;import org.junit.Test;import java.lang.reflect.Constructor;public class TestStudent {/*** 提取共有属性的构造器*/@Testpublic void getConstructors(){//a.第一步:获取类对象Class c=Student.class;//b.第二部:提取类中全部构造器对象Constructor[] constructors = c.getConstructors();//c.遍历构造器for (Constructor constructor : constructors) {System.out.println(constructor.getName()+"====>"+constructor.getParameterCount());}}/*** 提取所有构造器*/@Testpublic void getDeclaredConstructors(){//a.第一步:获取类对象Class c=Student.class;//b.第二部:提取类中全部构造器对象Constructor[] constructors = c.getDeclaredConstructors();//c.遍历构造器for (Constructor constructor : constructors) {System.out.println(constructor.getName()+"====>"+constructor.getParameterCount());}}@Testpublic void getConstructor() throws Exception {//a.第一步:获取类对象Class c=Student.class;//b.第二部:定位单个构造器对象 (按照参数定位无参构造器)Constructor cons = c.getConstructor();System.out.println(cons.getName()+"====>"+cons.getParameterCount());}@Testpublic void getDeclaredConstructor() throws Exception {//a.第一步:获取类对象Class c=Student.class;//b.第二部:定位某个有参构造器对象Constructor cons = c.getDeclaredConstructor(String.class,int.class);System.out.println(cons.getName()+"====>"+cons.getParameterCount());}
}
package org.example.reflect_constructer;import org.junit.Test;import java.lang.reflect.Constructor;public class TestStudent2 {//调用构造器得到一个对象并返回@Testpublic void getDeclaredConstructor() throws Exception {//a.第一步:获取类对象Class c=Student.class;//b.第二部:定位某个有参构造器对象Constructor cons = c.getDeclaredConstructor();System.out.println(cons.getName()+"====>"+cons.getParameterCount());//如果遇到私有构造器,可以暴力反射cons.setAccessible(true);//权限被打开Student s= (Student) cons.newInstance();System.out.println(s);Constructor cons1 = c.getDeclaredConstructor(String.class,int.class);System.out.println(cons1.getName()+"====>"+cons1.getParameterCount());Student s1 = (Student) cons1.newInstance("孙悟空", 50000);System.out.println(s1);}}
4.反射获取成员变量对象
使用反射获取成员变量并使用
package org.example.reflect_filed;import org.junit.Test;import java.lang.reflect.Field;public class FiledDemo01 {//1.获取全部成员变量@Testpublic void getDeclaredFields(){//a.定位class对象Class c=Student.class;//b.定位全部成员变量Field[] fields = c.getDeclaredFields();//c.遍历成员变量for (Field field : fields) {System.out.println(field.getName()+"==>"+field.getType());}}//2.获取某个成员变量@Testpublic void getDeclaredField() throws Exception {//a.定位class对象Class c=Student.class;//b.根据名称定位某个成员变量Field field = c.getDeclaredField("age");System.out.println(field.getName()+"==>"+field.getType());}
}
package org.example.reflect_filed;import org.junit.Test;import java.lang.reflect.Field;public class FieldDemo02 {@Testpublic void setField() throws Exception {//a.定位class对象Class c=Student.class;//b.根据名称定位某个成员变量Field field = c.getDeclaredField("age");field.setAccessible(true);//c.赋值Student s=new Student();field.set(s,18);System.out.println(s);//d.取值int age = (int) field.get(s);System.out.println(age);}
}
5.反射获取方法对象
package org.example.reflect_method;public class Dog {private String name;public Dog() {}public Dog(String name) {this.name = name;}public void run(){System.out.println("狗跑得很快~~");}public void eat(){System.out.println("狗吃骨头~~");}public String eat(String name){System.out.println("狗吃"+name);return "吃得很开心";}public String getName() {return name;}public void setName(String name) {this.name = name;}
}
package org.example.reflect_method;import org.junit.Test;import java.lang.reflect.Method;public class MethodDemo {//1.获取类中所有成员方法对象@Testpublic void getDeclaredMethods(){//a.获取类对象Class c=Dog.class;//b.提取全部方法:包括私有Method[] methods = c.getDeclaredMethods();//c.遍历全部方法for (Method method : methods) {System.out.println(method.getName()+"====>"+method.getReturnType()+"===>"+method.getParameterCount());}}//2.获取类中某个成员方法对象@Testpublic void getDeclaredMethod() throws Exception {//a.获取类对象Class c=Dog.class;//b.提取全部方法:包括私有Method m = c.getDeclaredMethod("eat");Method m2 = c.getDeclaredMethod("eat",String.class);m.setAccessible(true);//c.触发方法的执行Dog d=new Dog();//注意:如果方法是没有结果回来的,那么返回的是nullObject rs = m.invoke(d);System.out.println(rs);Object rs2 = m2.invoke(d, "骨头");System.out.println(rs2);}
}
6.反射的作用—泛型擦除
package org.example.reflect_genericity;import java.lang.reflect.Method;
import java.util.ArrayList;public class ReflectDemo {public static void main(String[] args) throws Exception {//需求:反射实现泛型擦除后,加入其他类型的元素ArrayList<String> list1=new ArrayList<>();ArrayList<Integer> list2=new ArrayList<>();System.out.println(list1.getClass());System.out.println(list2.getClass());System.out.println(list1.getClass()==list2.getClass());System.out.println("==========================");list2.add(23);list2.add(34);Class c=list2.getClass();//定位c类中的add方法Method add=c.getDeclaredMethod("add",Object.class);boolean rs = (boolean) add.invoke(list2, "孙悟空");System.out.println(list2);System.out.println(rs);}
}
7.反射的作用—通用框架的底层原理
package org.example.reflect_framerwork;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;public class MybatisUtils {public static void save(Object o) {try (PrintStream ps=new PrintStream(new FileOutputStream("junit-reflect-app/src/data.txt",true));){//1.提取这个对象的全部成员变量,只有反射可以解决Class c=o.getClass();//c.getSimpleName()获取当前类名 c.getName()获取包名+类名ps.println("=============="+c.getSimpleName()+"===================");Field[] fields = c.getDeclaredFields();//2.获取成员变量信息for (Field field : fields) {field.setAccessible(true);String name=field.getName();//3.提取本成员变量在obj中的值(取值)String value = field.get(o) + "";ps.println(name+"="+value);}} catch (Exception e) {e.printStackTrace();}}
}
package org.example.reflect_framerwork;/*** 目标:提供一个通用对象,支持保持所有对象的具体信息**/
public class ReflectDemo {public static void main(String[] args) {Student s=new Student();s.setName("孙悟空");s.setSex('男');s.setAge(10000);s.setNumber(1956842);MybatisUtils.save(s);Teacher t=new Teacher();t.setName("如来");t.setSalary(12265.0);MybatisUtils.save(t);}
}
package org.example.reflect_framerwork;public class Student {private String name;private int age;private long number;private char sex;public Student() {}public Student(String name, int age, long number, char sex) {this.name = name;this.age = age;this.number = number;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public long getNumber() {return number;}public void setNumber(long number) {this.number = number;}public char getSex() {return sex;}public void setSex(char sex) {this.sex = sex;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", number=" + number +", sex=" + sex +'}';}
}
package org.example.reflect_framerwork;public class Teacher {private String name;private double salary;public Teacher() {}public Teacher(String name, double salary) {this.name = name;this.salary = salary;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}@Overridepublic String toString() {return "Teacher{" +"name='" + name + '\'' +", salary=" + salary +'}';}
}
总结
本节主要介绍的是单元测试的基本用法和反射常见的API,并介绍了反射的作用,做高级框架和泛型擦除。