我正在练习 JUnit 测试用例,目前正在解决如下问题:
- 要从任何网站读取 HTML,请说“http://www.google.com”(考生可以使用 Java 中内置 API 中的任何 API,例如 URLConnection )。
- 在控制台上打印上述 URL 中的 HTML,并将其保存到本地计算机中的文件 (web-content.txt)。
- 为上述程序编写 JUnit 测试用例。
我已经成功实现了第一步,但是当我运行 JUnit 测试用例时,它显示失败。
ReadFile.java
package com.test;
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.test;
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 java.lang.AssertionError at org.junit.Assert.fail(Assert.java:86) at org.junit.Assert.assertTrue(Assert.java:41) at org.junit.Assert.assertTrue(Assert.java:52) at com.test.ReadFileTest.test(ReadFileTest.java:15) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown
我希望 JUnit 测试用例返回 true。
最佳答案
这里不起作用的是:
assertTrue(baos.toString().contains("http://google.co.in"));
有效的是
assertTrue(baos.toString().contains("google.co.in")); // note the difference
关于java - 如何用Java生成JUnit测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41148261/