Java基础之单元测试与包装类

Java 中的Junit单元测试

步骤

1.选中当前工程添加Junit4

2.创建Java类要求:

此类是public的此类提供一个无参构造器

此类声明单元测试的方法,

此时的单元测试方法:方法权限public,没有返回值,没有形参

此单元测试方法上需要声明注解@Test,并在单元测试中导入import org.junit.Test;

声明好单元测试方法以后,就可以在方法体内测试相关的代码

写完代码后双击单元测试方法名右键:run as - JUnit Test

说明

如果执行结果没有异常是绿条;有异常是红

包装类

针对八种基本数据类型定义相应的引用类型—包装类(封装类)

有了类的特点,就可以调用类中的方法,Java才是真正的面向对象

基本类型、包装类与String类间的转换 

 基本数据类型

测试基本数据类型----》包装类:调用包装类的构造器

   @Test
    //基本数据类型----》包装类:调用包装类的构造器
    public void test1(){
        int num1 = 10;
        //System.out.println();
        Integer in1= new Integer(num1);
        System.out.println(in1.toString());
       // Integer in2 = new Integer("123abc");//异常
       // System.out.println(in2.toString());
        Float f1 = new Float(12.3);
        Float f2 = new Float("12.4f");
        System.out.println(f1);
        System.out.println(f2);
        Boolean b1 = new Boolean("true");//true
        Boolean b2 = new Boolean(true);//true
        Boolean b3 = new Boolean("true123");//false


    }
测试结果
10
12.3
12.4

  包装类转换基本数据类型:调用包装类的xxxValue()

  @Test
    //包装类转换基本数据类型:调用包装类的xxxValue()
    public void  test2(){
        Integer in1 = new Integer(12);
        int i1=in1.intValue();
        System.out.println(i1);

    }
测试结果
12

  自动拆箱自动装箱

  @Test
    /*
    自动装箱和拆箱
     */
    public void test3(){

        int num1 = 10;
        //自动装箱
        Integer num3 = num1;
        method(num1);
        boolean b1=true;
        Boolean b2 =b1;//自动装箱
        //自动拆箱
        System.out.println(num3.toString());
        int num2 = num3;

    }
    public void  method(Object obj){

    }
测试结果
10

基本数据类型包装类----》string类型。调用String重载的valueOf()方法

@Test
    /*
    基本数据类型包装类----》string类型。调用String重载的valueOf()方法
     */
    public void  test4(){
        int num = 10;
        //方式1:连接运算
        String str1 = num +"";
        //方式2:调用String的方法
        float f1= 12.3f;
        System.out.println(String.valueOf(f1));

        double d1= new Double(123.3);
        //包装类转换String
       // String st3 = String.valueOf(d1);
    }
测试结果
12.3

  String 类型-----》基本数据类型、包装类:调用包装类的parsXXXX()方法

@Test
    public void test5(){
        String st1 =  "123";
        //String 转换包装类
        int in1 = Integer.parseInt(st1)+8;
        System.out.println(in1);

    }
测试结果
131

  示例

 @Test
    public  void  test6(){
        Integer i = new Integer(1);
        Integer j = new Integer(1);
        System.out.println(i==j);//fales
        Integer m= 1;
        Integer n = 1;
        System.out.println(m==n); //true
        //Integer 内部定义一个IntegerCache类定义一个Integer[]
        //范围是-128到127,保存了-128~127的整数范围。如果使用自动装箱方式
        //给Integer赋值的范围在-128~127范围时,直接使用数组里的元素,
        //不在用new了。目的,提高效率

        Integer x= 128;//new 的对象
        Integer y =128;//nwe 的对象
        System.out.println(x==y);//fales
    }
结果
false
true
false

  

草都可以从石头缝隙中长出来更可况你呢
原文地址:https://www.cnblogs.com/rdchenxi/p/14636535.html