【发布时间】:2017-02-01 21:55:35
【问题描述】:
cookie 中有一个 authtoken,用于验证用户,但是当我尝试使用 Nunit 和 cmd 运行 selenium C# 测试用例代码时,chrome 实例启动并且没有 cookie,因此它会将我重定向到登录页面。问题是为什么在测试期间启动的实例中没有 cookie 以及我如何解决这个问题。 这是我的代码。
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace AutomationTest
{
[TestFixture]
public class SeleniumTest
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[SetUp]
public void SetupTest()
{
driver = new ChromeDriver();
baseURL = "http://localhost/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
//try
//{
// driver.Quit();
//}
//catch (Exception)
//{
// // Ignore errors if unable to close the browser
//}
//Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheSTest()
{
driver.Navigate().GoToUrl(baseURL + "/TrailHead/");
driver.FindElement(By.Id("addNewLeadButton")).Click();
driver.FindElement(By.CssSelector("td.formTitle > input.td-button")).Click();
driver.FindElement(By.Id("township")).Clear();
driver.FindElement(By.Id("township")).SendKeys("2n");
driver.FindElement(By.Id("range")).Clear();
driver.FindElement(By.Id("range")).SendKeys("2e");
driver.FindElement(By.Id("section")).Clear();
driver.FindElement(By.Id("section")).SendKeys("2");
driver.FindElement(By.Id("legal")).Clear();
driver.FindElement(By.Id("legal")).SendKeys("2");
driver.FindElement(By.Id("NRI")).Clear();
driver.FindElement(By.Id("NRI")).SendKeys("2");
driver.FindElement(By.Id("NMA")).Clear();
driver.FindElement(By.Id("NMA")).SendKeys("2");
driver.FindElement(By.Id("tractAskedPrice")).Clear();
driver.FindElement(By.Id("tractAskedPrice")).SendKeys("2");
driver.FindElement(By.CssSelector("div.modalFooter > div.footer-right-button-save")).Click();
driver.FindElement(By.XPath("//div[@onclick='saveAndExit()']")).Click();
// Warning: assertTextPresent may require manual changes
Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.CssSelector("BODY")).Text, "^[\\s\\S]*$"));
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText()
{
try
{
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert)
{
alert.Accept();
}
else
{
alert.Dismiss();
}
return alertText;
}
finally
{
acceptNextAlert = true;
}
}
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!看来您需要学习使用调试器。请帮助自己一些complementary debugging techniques。如果之后仍有问题,请随时回来提供更多详细信息。
标签: c# asp.net-mvc selenium cookies nunit