一套测试就是一个强大的bug侦测器,能够大大的缩短查找bug的时间。
本次我们主要了解使用Junit对代码进行测试。
Junit中有以下这些方法可以对结果进行判定:
| assertArrayEquals(expecteds, actuals) | 查看两个数组是否相等。 |
| assertEquals(expected, actual) | 查看两个对象是否相等。类似于字符串比较使用的equals()方法 |
| assertNotEquals(first, second) | 查看两个对象是否不相等。 |
| assertNull(object) | 查看对象是否为空。 |
| assertNotNull(object) | 查看对象是否不为空。 |
| assertSame(expected, actual) | 查看两个对象的引用是否相等。类似于使用“==”比较两个对象 |
| assertNotSame(unexpected, actual) | 查看两个对象的引用是否不相等。类似于使用“!=”比较两个对象 |
| assertTrue(condition) | 查看运行结果是否为true。 |
| assertFalse(condition) | 查看运行结果是否为false。 |
| assertThat(actual, matcher) | 查看实际值是否满足指定的条件 |
| fail() | 让测试失败 |
现在我们来测试文件读取器FileReader
第一步:准备一个测试文件read,可以是任意格式的文件,内容如下:
Lily 1 90 80 72
Jack 2 88 91 80
Peter 3 69 93 70
第二步:创建一个测试类TestFileReader
package File; import static org.junit.Assert.*; import java.io.FileReader; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestFileReader { }
第三步:添加setUp和tearDown方法
setup用于产生文件读取对象,teardown用于删除文件对象,因为Java中有自带的垃圾回收处理机制,所以不需要额外的删除对象,在这里我们使用teardown用来关闭文件。
public class TestFileReader { FileReader _input; @Before public void setUp() throws Exception { try { _input = new FileReader("E:/code/Rent/src/File/read"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("file can't open"); } } @After public void tearDown() throws Exception { try { _input.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("file can't close"); } } }