package htmlunit;
import org.junit.Assert;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class Test {
public static void main(String[] args) throws Exception {
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
Assert.assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
final String pageAsXml = page.asXml();
Assert.assertTrue(pageAsXml.contains("<body class=\"composite\">"));
final String pageAsText = page.asText();
Assert.assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
if(Assert.assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"))){
System.out.println("true");
} else {
System.out.println("false");
}
System.out.println("test");
webClient.closeAllWindows();
}
}
为什么我在Eclipse中运行它,那么这只返回“test”?如何打印Asserts的结果?
if(Assert.assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"))){
System.out.println("true");
} else {
System.out.println("false");
}
我有这个错误:
类型不匹配:无法从void转换为boolean
如何将if
与Assert
一起使用?
答案 0 :(得分:4)
assertTrue()
返回void
,因此您不能将其用作if
语句的表达式。只要您在JUnit框架内正确使用它们,JUnit断言就会在失败时自动打印错误消息。
答案 1 :(得分:3)
Assert.assertTrue
无效返回。如果输入不正确,则抛出异常。这在您想要崩溃的测试中很有用,表明存在问题。
在您的情况下,您只需要if(condition)
,而不是if(Assert.assertTrue(condition))
。你实际上并没有Assert的用例。