我正在练习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 Test时遇到以下错误:
java.lang.AssertionError 位于org.junit.Assert.assertTrue(Assert.java:41)org.junit.Assert.assertTrue(Assert.java:41)org.junit.Assert.fail(Assert.java:86)的java.lang.AssertionError(Assert.java:52) at com.sudhir.ReadFileTest.test(ReadFileTest.java:15)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown
我希望JUnit测试用例返回true。
答案 0 :(得分:2)
这里没有的是:
assertTrue(baos.toString().contains("http://google.co.in"));
什么可行?
assertTrue(baos.toString().contains("google.co.in")); // note the difference
答案 1 :(得分:0)
做出类似的事情:
static String display(String input) {
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;
StringBuilder builder = new StringBuilder();
while ((data = reader.read()) != -1) {
builder.append((char) data);
}
return builder.toString();
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
我不知道你为什么使用ByteArrayOutputStream
现在为您的测试用例:
@Test
public void test() {
String data = ReadFile.display("http://google.co.in");
assertTrue(data != null);
assertTrue(data.contains("http://google.co.in"));
}