我正在使用 UP Design 开发一个下载管理器。在这个细化迭代中,我的主要用例:下载文件。这里是 Download.java
public class Download implements Runnable {
// Max size of download buffer.
private static final int MAX_BUFFER_SIZE = 1024;
// These are the status names.
public static final String STATUSES[] = {"Downloading", "Complete"};
// These are the status codes.
public static final int DOWNLOADING = 0;
public static final int COMPLETE = 1;
public static void main(String[] args) throws MalformedURLException {
System.out.println("Welcome to Download Manager.");
System.out.println("Enter a URL.");
URL url;
String s;
Scanner scan= new Scanner(System.in);
s=scan.nextLine();
url= new URL(s);
Download download=new Download(url);
}
private URL url; // download URL
private int size; // size of download in bytes
private int downloaded; // number of bytes downloaded
private int status; // current status of download
// Constructor for Download.
public Download(URL url) {
this.url = url;
size = -1;
downloaded = 0;
status = DOWNLOADING;
// Begin the download.
download();
}
// Start or resume downloading.
private void download() {
System.out.println("Starting.");
Thread thread = new Thread(this);
thread.start();
}
// Download file.
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
int contentLength = connection.getContentLength();
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
}
// Open file and seek to the end of it.
file = new RandomAccessFile(getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
System.out.print("%"+(downloaded/size)+'\r');
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1){
System.out.println("File was downloaded");
break;
}
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
}
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
}
} catch (Exception e) {
System.out.println("Error!");
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}
我该如何编写此代码的测试代码?例如我应该测试URL验证,还是应该控制文件是否正在下载?我该如何进行这些测试?谢谢。