shikamaru nara
shikamaru nara

Reputation: 5

How do you assert/ validate if all checkbox are selected in C# selenium

I have created a method in C# selenium that selects all the checkbox. I need to validate if all the check box are selected

 public Page selectallcheckbox()
    {
        PrShared.Page.SwitchToFrame("IFrame");
        foreach (IWebElement e in Driver.Instance.FindElements(By.XPath("//input[@class ='highlightCheck']")))
        {
            if (!e.Selected)
                e.Click();
        }
        Driver.Instance.webDriver.SwitchTo().ParentFrame();
        return this;
    }

// This code below asserts if all check box is selected. Is there a better way to assert than what I have below?

    public Page validatecheckbox()
    {
        string selectedcheckbox = Driver.Instance.FindElement(By.XPath("//[@id='TR14']")).Text.ToString().Trim();
        string expectedcheckboxvalue = "test checkbox one, text checkbox2, tect checkbox3, so on";
        Assert.AreEqual(expectedcheckboxvalue, selectedcheckbox);
        return this;
    }

Upvotes: 0

Views: 1018

Answers (1)

JD2775
JD2775

Reputation: 3801

If you wanted to keep your original selectallcheckbox as returning an object of Page then I would do something like this below...

Add another method beneath the selectallcheckbox method

    public bool checkAllCheckBoxes()
    {
        selectallcheckbox();
        string element = "//input[@class ='highlightCheck']";
        PrShared.Page.SwitchToFrame("IFrame");
        foreach (IWebElement e in Driver.Instance.FindElements(By.XPath(element)))
        {
            if (e == false)
            {
                return false;
            }
        }
        return true;
    }

This will execute selectallcheckbox method first and then loop through the elements again and return true if all boxes are checked or false if they aren't. If a box is checked, it is true by definition, false if not.

You can take this a step further if you want and remove the common code in both methods into a single method which you then call, to reduce repeated code.

Then in your assert you could just do something like this:

var allboxeschecked = checkAllCheckBoxes();
Assert.IsTrue(allboxeschecked);

This obviously isn't tested against your use-case so you may need to make adjustments where necessary.

Upvotes: 1

Related Questions