How to Assert value assigned to ElementId in Selenium c#?

1.2k views Asked by At

This is supposed to be easy, but somehow I couldn't get this to work as I would have liked to. I am trying to assert on Account value from below piece of code, which does have an ElementId assigned.

My aim is to verify that Account value is greater than zero (or can also do != zero)

I am confused whether to use the GetAttribute or shall I just extract the text out of the ElementId?

<div class="col-md-6 col-sm-12 w-create-account">
<label class="w-label">Value</label>
<h2 id="account-value">$1,00,000</h2>
</div>

I am using Selenium(C#) on NUnit. Any help is appreciated..!!

3

There are 3 answers

1
Mahipal On BEST ANSWER

You can do something similar to following:

public static decimal ConvertToNumber(string str)
{
    return decimal.Parse(str, NumberStyles.Currency);
}


[Test]
public void TestAccountValue()
{

    Assert.IsTrue(ConvertToNumber(driver.FindElement(By.XPath("//div[contains(@class, 'w-create-account']/h2")).Text) > 0, "Account value is not greater than zero.");

}

Let me know, if you have any further queries.

0
Subburaj On

You can use the below logic for the assertion

Code:

var accountValue=driver.FindElement(By.Id("account-value")).Text;
accountValue = accountValue.Substring(1);//Inorder to remove the currency symbol.

var amount = Decimal.Parse(accountValue);

Assert.IsTrue(amount > 0);//If the Amount value is greater than 0, then assertion wil be passed.

Suppose, if the account value holds negative balance as well, then replace the substring statement with the below condition

var accountValue=driver.FindElement(By.Id("account-value")).Text;

if (accountValue.Contains('-')){
    accountValue = "-" + accountValue.Substring(2);//Inorder to remove the currency symbol and negative sign
}
else
{
    accountValue = accountValue.Substring(1);//Inorder to remove the currency symbol.
}

var amount=Decimal.Parse(accountValue);

Assert.IsTrue(amount > 0);//If the Amount value is greater than 0, then assertion wil be passed.
0
martin pb On

I am using this one in pricing services:

Assert.Greater(Convert.ToDouble(driver.FindElement(By.Id("account-value")).Text), 0,  
 "Acccount value is zero 0");

-- it means, if Account value is zero, it failed.

or if you want to add assert for zero. it could be like:

string accountValue = driver.FindElement(By.Id("account-value")).Text;  
Assert.IsFalse(accountValue.Contains("0"), "Account value is zero");  

-- I hope it is displayed as text, if not, you need to use .GetAttribute("value") = number.