时间:2018-07-25
作者:魏文应
一、Junit 单元测试方法
一般情况下,main() 方法就是程序的入口。但在测试时,我们只希望运行一些当前类的某些方法。这时,我们就可以使用 @Test
。首先,在 Eclipse 的 添加 Junit 库:选中 JAVA工程中,右键 -> Build Path -> Add Libraries -> 选择Junit -> Next -> 选择Junit4 -> Finish 。
-
Junit选择
然后就可以在Package Explorer 中,看到Junit库在当前工程项目中了。
-
Junit库
然后再代码中:
import org.junit.Test;
public class TestJunit {
public static void main(String[] args) {
String str = "main";
System.out.println(str);
}
@Test
public void test1() {
String str = "test1";
System.out.println(str);
}
}
那么,main()方法 和 test1()方法都可以成为 程序的入口。测试时,然后编译运行,Eclipse 会提示选择你选择哪个方法作为 程序的入口。如果选择 test1()方法作为程序入口,此时test1()方法相当于main方法,也就是 main() 方法被 test1() 方法取代了。这样,就方便我们测试代码了。而不需要把代码都写进main()方法中去测试运行了。
二、包装类
针对八种基本定义相应的引用类型,称为 包装类(封装类) :
基本数据类型 | 包装类 |
---|---|
boolean | Boolean |
byte | Byte |
short | Short |
char | Character |
int | Integer |
long | Long |
float | Float |
double | Double |
这样,使得变量类型有了类的特点,可以调用一些类的方法。下面方式,可以 使用一个包装类:
import org.junit.Test;
public class TestWrapper {
@Test
public void test1(){
Integer i = new Integer(12);
System.out.println(i);
}
}
这样,就可以定义一个 Integer 包装类,并赋值为12。如何 将包装类的数值,赋值给一个基本类型变量 呢?看下面方法:
import org.junit.Test;
public class TestWrapper {
@Test
public void test1(){
Integer i = new Integer(12);
int i2 = i.intValue();
System.out.println(i);
}
}
这样,通过包装类内的方法,比如:对于 Integer 包装类来说,使用 Ineger 类的 intValue() 方法,可将值赋值给基本类型变量。
自动装箱和拆箱
在 JDK5.0 以后,引入了自动装箱和拆箱的概念。
import org.junit.Test;
public class TestWrapper {
@Test
public void test1(){
int i = 12;
Integer i2 = i; // 自动装箱
System.out.println(i2);
}
}
上面 基本变量 i
可以直接赋值给包装类Integer i2
,而不需要 Integer i = new Integer(12);
这种方式赋值,这就是 自动装箱 。看下面自动拆箱:
import org.junit.Test;
public class TestWrapper {
@Test
public void test1(){
Integer i = 12; // 自动装箱
int i2 = i; // 自动拆箱
System.out.println(i2);
}
}
自动拆箱,是将 Integer 包装类 i
直接赋值给了基本数据类型 int 变量 i2
,而不需要 int i2 = i.intValue();
这种赋值方式,这就是 自动拆箱 。
操作类输入参数是字符
下面代码中,包装类参数直接输入 数值 12
:
import org.junit.Test;
public class TestWrapper {
@Test
public void test1(){
Integer i = new Integer(12);
System.out.println(i);
}
}
事实上,参数还可以是 字符串 :
import org.junit.Test;
public class TestWrapper {
@Test
public void test1(){
Integer i = new Integer("12");
System.out.println(i);
}
}
输入字符要注意: 字符串内容,必须是相对应的基本类型变量。比如 Integer("1234567")
是没有问题的,但如果是 Integer("12hijklmn")
,运行时就会报 java.lang.NumberFormatException
错误。不过,Boolean 包装类是比较特殊的,除了 Boolean("true")
返回 true 以外,比如 Boolean("true12133")
、Boolean("truefalse")
、Boolean("false")
等,都返回 flase 。
数据类型的转换
基本数据类型、包装类 转换为 String类 ,使用的是 String 类的 valueOf() 方法:
import org.junit.Test;
public class TestWrapper {
@Test
public void test2(){
int i = 10;
String str = String.valueOf(i);
System.out.println(str);
}
}
String类 转换为 基本数据类型、包装类,使用的是对应包装类的 parseXxx(String str) 方法:
import org.junit.Test;
public class TestWrapper {
@Test
public void test2(){
String str = "12";
int i = Integer.parseInt(str);
System.out.println(i);
}
}
网友评论