【问题标题】:How to verify that text is present on webpage or not with NUnit and C#如何使用 NUnit 和 C# 验证网页上是否存在文本
【发布时间】:2017-11-22 19:28:24
【问题描述】:

我正在尝试验证应用程序登录页面上的文本可用性。

我该怎么做?

使用以下代码,我可以验证文本是否存在,但是我坚持针对每个条件打印文本,所以如果文本错误,那么测试用例应该会失败。

public void Readcontent()
{
    using (WebClient client = new WebClient())
    {
        // string Test = "By logging on you can Ask the our experts your questions by email....";
        string Test;
        string url = "https://sampleweb.com";
        string content = client.DownloadString(url);
        if (content.Contains("XYZ"))
        {
            Console.WriteLine("Expected Text found here: ");
        }
        else
        {
            Console.WriteLine("Expected Text NOT found here: ");
        }
        Console.WriteLine(content);
}

【问题讨论】:

  • 您真的是要测试后端生成的网页上呈现的内容吗?在这种情况下,您可能需要查看基于浏览器的 javascript 单元测试框架。试试这个链接msdn.microsoft.com/en-us/library/…
  • NUnit 是一个单元测试框架。它没有用于 UI 或 Web 应用程序测试的任何特定功能。你在使用 selenium 之类的浏览器自动化框架吗?
  • 是的 mike z 我正在使用 selenium 框架

标签: c# string unit-testing nunit


【解决方案1】:

NUnit 具有用于字符串断言的类StringAssert。该类有方法Contains:

[Test]
public void DownloadStringTest()
{
    using (WebClient client = new WebClient())
    {
        string url = "https://sampleweb.com";
        string content = client.DownloadString(url);
        StringAssert.Contains("XYZ", content, "Expected Text NOT found");
    }
}

StringAssert 也有 StartsWithEndsWithAreEqualIgnoringCase 方法。

【讨论】:

    【解决方案2】:

    我将您的问题解释为“当 content.Contains("XYZ") 为假时,我如何让测试失败?”。为此,您需要添加一个断言。

    Assert.That(actual, Contains.Substring(expected), "Error message");
    

    在你的代码中:

    [Test]
    public void Readcontent()   
    {
        using (WebClient client = new WebClient())
        {
            string url = "https://sampleweb.com";
            string content = client.DownloadString(url);
            Assert.That(content, Contains.Substring("XYZ"), "String not found in entire page content.");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多