【问题标题】:How can I use Assert in Unit Testing? [closed]如何在单元测试中使用 Assert? [关闭]
【发布时间】:2014-08-17 20:26:53
【问题描述】:
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 中运行它,然后它只返回“测试”?如何打印 Asserts 的结果?

        if(Assert.assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"))){
            System.out.println("true");
        } else {
            System.out.println("false");
        }

我有那个错误:

类型不匹配:无法从 void 转换为布尔值

如何将ifAssert 一起使用?

【问题讨论】:

  • 您需要阅读更多关于 JUnit 和建议的单元测试结构的信息。

标签: java eclipse junit


【解决方案1】:

assertTrue() 被声明为返回void,因此您不能将其用作if 语句的表达式。只要您在 JUnit 框架中正确使用它们,JUnit 断言就会在它们失败时自动打印错误消息。

【讨论】:

  • 好的,那为什么不显示来自 junit 的任何消息?
  • @darlik 因为除了 Assert 类之外,您根本没有使用 JUnit 框架。我建议您做一些研究并阅读有关如何在 JUnit 测试中组织代码的信息。
【解决方案2】:

Assert.assertTrue 是无效返回。如果输入不正确,它会抛出异常。这在您希望崩溃以表明存在问题的测试中很有用。

在您的情况下,您只需要if(condition),而不是if(Assert.assertTrue(condition))。您实际上没有 Assert 的用例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多