我在練JUnit測試案例和目前的工作是如下問題:如何在Java中生成JUnit測試用例?
- 可以從任何網站閱讀HTML說「http://www.google.com」(考生可使用的Java一樣的URLConnection內置的API的任何API)。
- 在控制檯上打印上述URL中的HTML並將其保存到本地計算機上的文件(web-content.txt)。
- 爲上述程序編寫JUnit測試用例。
我已經成功實現了第一步,但是當我運行JUnit Test Case時顯示失敗。
ReadFile.java
package com.sudhir;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ReadFile
{
static void display(String input,OutputStream fos)
{
try
{
URL url = new URL(input);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
Reader reader = new InputStreamReader(stream);
int data=0;
while((data=reader.read())!=-1)
{
System.out.print((char)data);
fos.write((char)data);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input =null;
FileOutputStream fos =null;
System.out.println("Please enter any url");
try
{
input = reader.readLine();
fos = new FileOutputStream("src/web-context.txt");
display(input,fos);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
ReadFileTest.java
package com.sudhir;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
public class ReadFileTest {
@Test
public void test() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ReadFile.display("http://google.co.in", baos);
assertTrue(baos.toString().contains("http://google.co.in"));
}
}
我得到,而在Eclipse中運行JUnit測試以下錯誤:
的java.lang。 AssertionError
你有什麼例外? – thepaulo
請分享整個錯誤日誌和預期輸出。 – nullpointer
java.lang.AssertionError \t在org.junit.Assert.fail(Assert.java:86) \t在org.junit.Assert.assertTrue(Assert.java:41) \t在org.junit.Assert.assertTrue (Assert.java:52) \t在com.sudhir.ReadFileTest.test(ReadFileTest.java:15) \t在sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法) \t在sun.reflect.NativeMethodAccessorImpl.invoke(未知 我想讓JUnit測試用例返回true –