Fetch the repository succeeded.
package com.itheima.a05junitdemo1;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class JunitDemo3 {
//在实际开发中,真正完整的单元测试该怎么写?
//前提:
//以后在工作的时候,测试代码不能污染原数据。(修改,篡改)
//1.利用Before去对数据做一个初始化的动作
//2.利用Test真正的去测试方法
//3.利用After去还原数据
//需求:测试File类中的delete方法是否书写正确??
@Before
public void beforemethod() throws IOException {
//先备份
File src = new File("C:\\Users\\曾铖坚\\Desktop\\a.txt");
File dest = new File("C:\\Users\\曾铖坚\\Desktop\\copy.txt");
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
int len;
while ((len = fis.read()) != -1) {
fos.write(len);
}
fos.close();
fis.close();
}
//问题:咱们现在有没有污染原数据?
//有当测试代码运行之后,a.txt被删除了
//作为一个标准的测试人员,运行完单元测试之后
//1.得到结果
//2.a.txt还在
@Test
public void method() {
File file = new File("C:\\Users\\曾铖坚\\Desktop\\a.txt");
boolean result = file.delete();
//检测a.txt是否存在
boolean exists = file.exists();
//只有同时满足了下面所有的断言,才表示delete方法编写正确
Assert.assertEquals("delete方法有问题", result, true);
Assert.assertEquals("文件还存在", exists, false);
}
@After
public void aftermethod() throws IOException {
//对a.txt文件进行还原
File src = new File("C:\\Users\\曾铖坚\\Desktop\\copy.txt");
File dest = new File("C:\\Users\\曾铖坚\\Desktop\\a.txt");
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
int len;
while ((len = fis.read()) != -1) {
fos.write(len);
}
fos.close();
fis.close();
//删除备份文件
src.delete();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。