单元测试
Junit:JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个。 JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。
步骤
1.编写测试类。
2.编写测试方法, public void 方法名() {}, public void固定了,不能有参数。
3.在测试方法头上添加@Test注解。
4.运行测试方法。
5.看测试结果。
Class对象
(一)三种得到Class对象的方法
1.类名.class
2.对象.getClass()
3.Class.forName(类全名);
public class Demo04 {
public static void main(String[] args) throws ClassNotFoundException {
// 1.类名.class
Class cls1 = Employee.class;
System.out.println(cls1); // class com.itheima.bean.Employee
// 2.对象.getClass()
Employee e = new Employee();
Class cls2 = e.getClass();
System.out.println(cls2); // class com.itheima.bean.Employee
// 3.Class.forName(类全名); // 类全名就是包名.类名
Class cls3 = Class.forName("com.itheima.bean.Employee");
System.out.println(cls3); // class com.itheima.bean.Employee
System.out.println(cls1 == cls2);
System.out.println(cls1 == cls3);
}
}
(二)通过反射技术获取构造方法对象,并创建对象。
1.先得到Class对象
2.通过Class对象获取Constructor
3.Constructor的newInstance()方法创建对象
(三)通过反射获取成员方法对象,并且调用方法。
1.获取Class对象
2.通过Class对象获取Method
3.让Method对象调用invoke();
注解
(一)注解的作用:注解给程序使用的, 可以给类携带额外的信息。
(二)自定义注解和使用注解
自定义注解格式:
@inerface {
数据类型 属性名();
}
使用注解格式:
@注解名(属性名1=属性值1, 属性名2=属性值2…)
(三)说出常用的元注解及其作用
元注解的作用:修饰注解的注解
@Target: 限制注解能够放在哪些位置
@Retention: 限制注解能够存活多久
(四)解析注解并获取注解中的数据( 注解在谁头上,就用谁来获取注解)
1.获取类的Class对象
2.通过Class获取Method
3.通过Method获取注解
method.getAnnotations();
method.getAnnotation(BookAnno.class);
boolean b = method.isAnnotationPresent(BookAnno.class);
(五)MyTest案例
1.定义MyTest注解
2.定义一个类,里面包含多个方法
3.一些方法添加@MyTest注解
4.解析注解,获取Class对象
5.创建一个对象
6.获取所有的Method
7.遍历所有的Method,拿到每个Method
8.如果Method上有@MyTest,就运行该方法
public class Demo {
public static void main(String[] args) throws Exception {
// 4.解析注解,获取Class对象
Class cls = Class.forName("com..demo注解案例_模拟Junit.Student");
// 5.创建一个对象
Object obj = cls.newInstance();
// 6.通过反射获取所有的Method
Method[] methods = cls.getMethods();
// 7.遍历所有的Method,拿到每个Method
for (Method method : methods) {
// 判断method上有没有@MyTest注解
boolean b = method.isAnnotationPresent(MyTest.class);
if (b) {
// 8.如果Method上有@MyTest,就运行该方法
method.invoke(obj);
}
}
}
}
// 1.定义MyTest注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTest {
}
// 2.定义一个类,里面包含多个方法
public class Student {
// 3.一些方法添加@MyTest注解
public void sleep() {
System.out.println("学生睡觉了");
}
@MyTest
public void getUp() {
System.out.println("学生起床了");
}
public void eat() {
System.out.println("学生吃饭了");
}
@MyTest
public void study() {
System.out.println("学生色色发抖的学习了");
}
}