反射应用单体测试例子

news/2024/5/19 6:59:20 标签: java, 反射, 单体测试, unittest

采用反射的形式,进行类的单体测试
文件目录结构

java">com.Main
       Main.java
       Screen.java
com.UnitTest
       ScreenTest.java

Main.java

在Main.java中直接使用反射的方式,调用Screen.java的接口,在ScreenTest中采用单体测试反射调用Screen

java">package com.Main;
import java.lang.reflect.*;
import com.Main.*;
public class Main {
	
	public static void main(String[] str) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, ClassNotFoundException, NoSuchMethodException, SecurityException {	
		//1
		Screen screen1 =new Screen();
		Class<?> clazz = screen1.getClass();
		//2
		Class<?> clazz1 = Screen.class;
		//3
		Class<?> clazz2 = Class.forName("com.Main.Screen");
		Screen s = (Screen)clazz2.newInstance();
		s.fun();
		//调用无参数
		try {
			System.out.println("-----------------调用无参");
			Class<?> cls = Screen.class;
			Method method = cls.getDeclaredMethod("fun", null);
			method.setAccessible(true);
			method.invoke(cls.newInstance());
			method.setAccessible(false);
		}catch(Exception e) {
			System.out.println(e.getStackTrace());
		}
		//调用有参
		try {
			System.out.println("-----------------调用有参");
			Class<?> cls = Screen.class;
			Class<?> []args = new Class[2];
			args[0]=String.class;
			args[1]=int.class;
			Method method = cls.getDeclaredMethod("fun1",args);//Method method = cls.getDeclaredMethod("fun1",String.class,int.class);
			method.setAccessible(true);
			method.invoke(cls.newInstance(),"123",123);
			method.setAccessible(false);
		}catch(Exception e) {
			System.out.println(e.getStackTrace());
		}
		//调用内部类
		try {
			System.out.println("-----------------调用内部类");
			Class<?> cls = Screen.class;
			Screen screen = (Screen)cls.newInstance();
			Class<?> cls1 = Class.forName("com.Main.Screen$Bluetooth");
			Constructor<?>[] constructor=cls1.getDeclaredConstructors();
			for(Constructor<?> con:constructor) {
				System.out.println(con);
			}
			constructor[0].setAccessible(true);
			Object obj = constructor[0].newInstance(screen);
			Method method = cls1.getDeclaredMethod("onChange",String.class,int.class);
			method.setAccessible(true);
			method.invoke(obj,"String",123);
			method.setAccessible(false);
			constructor[0].setAccessible(false);
		}catch(Exception e) {
			System.out.print(e.getStackTrace());
		}
	}

}

Screen.java

java">package com.Main;

public class Screen {
	private static Screen screen;
	public Screen() {
		
	}
	public Screen(int _a) {
		
	}
	//单例模式
	public static Screen getInstance() {
		if(screen==null) {
			screen = new Screen();
		}
		return screen;
	}
	public void fun() {
		System.out.println("fun() ");
	}
	public void fun1(String _string,int _num) {
		if("hello".equals(_string) && _num == 5) {
			System.out.println("fun1() "+_string+_num);
		}else {
			
		}	System.out.println("fun1() 没有走到的分支");
	}
	
	
	public class Bluetooth {
		public Bluetooth() {
			System.out.println(" Bluetooth()");
		}
		public Bluetooth(String _string) {
			System.out.println("Bluetooth(String _string)");
		}
		public void onChange(String string,int i) {
			System.out.println("Bluetooth类  onChange"+string+" "+i);
		}
	}
}

ScreenTest.java

java">package com.UnitTest;
import com.Main.*;
import com.Main.Screen.Bluetooth;

import org.junit.*;
import java.lang.reflect.*;
public class ScreenTest {
	
	private static Screen screen;
	
	
	public  Method getFatherMethod(Class<?> clazz,String methodName,final Class<?>[] classes) throws Exception{
		Method method=null;
		try {
			method=clazz.getDeclaredMethod(methodName, classes);
		}catch(NoSuchMethodException e) {
			if(clazz.getSuperclass()==null) {
				return method;
			}else {
				method = getFatherMethod(clazz.getSuperclass(),methodName,classes);
			}
			System.out.println("NoSuchMethodException"+e.getStackTrace());
		}
		return method;
	}
	public  Field getFatherField(Class<?> clazz,String methodName) throws Exception{
		Field field = null;
		try {
			field = clazz.getDeclaredField(methodName);
		}catch(NoSuchFieldException  e) {
			if(clazz.getSuperclass()==null) {
				return field;
			}else {
				field = getFatherField(clazz.getSuperclass(),methodName);
			}
			System.out.println("NoSuchFieldException"+e.getStackTrace());
		}
		return field;
	}
	
	@BeforeClass
	public static void BefoClass() {
		screen = Screen.getInstance();
	}
	@AfterClass
	public static void AfterClass() {
		System.gc();
	}
	@Test
	public void funTest() throws Exception {
		System.out.println("------------------1----begin---------------------");
		try {
			Method method = getFatherMethod(Screen.class,"fun", null);
			if(method!=null) {
				method.setAccessible(true);
				Object invoke = method.invoke(screen);
				if(invoke!=null) {
					System.out.println("invoke  sucess");
				}
				method.setAccessible(false);
			}
		}catch(Exception e) {
			System.out.println("funTest"+e.getStackTrace());
		}
		System.out.println("------------------1----end---------------------");
	}
	@Test
	public void fun1Test() throws Exception{
		System.out.println("------------------2----begin---------------------");
		try {
			Class<?>[] args1 = new Class[2];
			args1[0]=String.class;
			args1[1]=int.class;
			Method method = getFatherMethod(Screen.class,"fun1", args1);
			method.setAccessible(true);
			//method.invoke(screen, null,0);
			method.invoke(screen, "hello",5);
			method.setAccessible(false);			
		}catch(Exception e) {
			System.out.println("fun1Test "+e.getStackTrace());
		}
		System.out.println("------------------2----end---------------------");
	}
	
	@Test
	public void BluetoothTest() {
		System.out.println("------------------3----begin---------------------");
		try {
			Class<?> cls = Class.forName("com.Main.Screen$Bluetooth");
			if(cls != null) {
				System.out.println("------------------cls != null---------------------");
				Class<?>[] args= new Class[2];
				args[0]=String.class;
				args[1]=int.class;
				Method method = cls.getDeclaredMethod("onChange", args);
				
				method.setAccessible(true);
				Constructor<?>[]  constructor = cls.getDeclaredConstructors();
				for(Constructor<?> con:constructor) {
					System.out.println("Constructor<?>  "+con);
				}
				constructor[0].setAccessible(true);
				Object obj = constructor[0].newInstance(screen);//传一个外部类的对象进去		
				method.invoke(obj, "123",123);
				constructor[0].setAccessible(false);		
				method.setAccessible(false);
				
			}
		}catch(Exception e) {
			System.out.println("BluetoothTest "+e.getStackTrace());
		}
		System.out.println("------------------3----end---------------------");
	}
	
}


http://www.niftyadmin.cn/n/1035821.html

相关文章

基础篇 | 14 C++ 图像处理

Xcode下安装OpenCV OpenCV是一个非常完善的开源计算机视觉库&#xff0c;现在也支持CPU加速这个特性&#xff0c;它提供了C、C、Python、Matlab多种接口&#xff0c;并且是跨平台的&#xff0c;支持在Windows、Linux、macOS、Android、iOS。 现在我们来看一下如何在Xcode下下…

8.【Linux】ubuntu常用开发配置

配置开发环境 更新软件源以确保安装到的软件是最适合当前系统的版本&#xff08;必须&#xff09;&#xff1a; sudo apt-get update 安装和配置代码管理工具 git&#xff0c;记得把下面命令行中的名字和邮件替换成自己的&#xff08;必须&#xff09;&#xff1a; s…

java单体测试导入jar包

【Junit】JUnit-4.12使用报java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing错误 1.junit-4.12.jar 链接&#xff1a;https://pan.baidu.com/s/1QbF71PY-tKlPfvWK_90Teg 提取码&#xff1a;4q64 2.hamcrest-core-1.3.jar 链接&#xff1a;https://pan.baidu.com/…

基础篇 | 15 C++ 科学计算 - OpenBLAS的安装与使用

BLAS简介 类似于Anaconda里面的numpy&#xff0c;C里面也有类似的矩阵运算库&#xff0c;称之为BLAS&#xff08;Basic Linear Algebra Subprograms&#xff09;&#xff1a;基础线性代数子程序库。 支持的数据类型有&#xff1a; 单精度浮点数&#xff08;float&#xff09;…

基础篇 | 16 C++ 编程入门(七)虚函数

虚函数是C当中非常重要的概念&#xff0c;它事实上是C组装成完整程序当中最为重要的环节。如果大家不能理解虚函数是怎么工作的&#xff0c;能解决什么样的问题。这个事情是很麻烦&#xff0c;所以今天要我们来谈谈虚函数是怎么回事。 Virtual 的定义及作用 为了直观解释&am…

5.【Windows】Firefox启动选择用户配置文件

windows启动Firefox 出现需要选择用户配置文件 右键-》属性 在目标中添加 -profile “C:\Program Files\Mozilla Firefox\Profiles” "C:\Program Files\Mozilla Firefox\firefox.exe" -profile "C:\Program Files\Mozilla Firefox\Profiles"修改后为&am…

windows安装adb

1.下载 minimal_adb_fastboot_v1.4.3.zip 链接&#xff1a;https://pan.baidu.com/s/1CggnrrBzROf58AXbGFhlrw 提取码&#xff1a;p76y 2.配置环境变量 添加完成 查看是否adb 是否好用

基础篇 | 17 C++ 编程入门(八)类型转换与多重继承

C 其它类型转换 前面文章我们讲过dynamic_cast —> RTTI,static_cast;今天再讲讲reinterpret_cast ,const_cast,这些就是C里面的全部类型转换&#xff0c;这些都熟练掌握后&#xff0c;写C的类型转换会行云流水。 回顾一下之前&#xff1a; dynamic cast <-> RTTI(…