Search code examples
c#stringunit-testingnunit

How to verify that text is present on webpage or not with NUnit and C#


I'm trying to verify text availability on login page of application.

How can I do that?

Using following code I'm able to verify text present or not however I'm stuck to print text against each condition so if text is wrong then test case should get failed.

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);
}

Solution

  • NUnit has class StringAssert for string assertions. The class has method 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 also has StartsWith, EndsWith and AreEqualIgnoringCase methods.