我只是使用SpecFlow + Selenium + pageObject自动化网站。 当我初始化我的SignIn类的对象,然后我得到空指针异常。我尝试了LoginTest类(步骤定义文件)的构造函数内部但是同样的错误然后我移动到第一步定义然后它正在工作。新问题是我不能在第二步定义中使用相同的对象,因为它是在本地初始化的。
我正在添加我的代码,请告诉我我在所有脚本中犯了什么错误。
namespace UnitTestProject5.Pages
{
public class SignIn
{
public IWebDriver driver;
[FindsBy(How = How.XPath, Using ("//nav[@role='navigation']/div[3]/div[1]/div/div/div/ul/li[5]/a"))]
public IWebElement Login { get; set; }
public IWebElement Username;
public IWebElement Password;
public IWebElement Signin;
public SignIn(IWebDriver driver)
{
this.driver = driver;
}
public void LoginToMyAccount(String username,String password)
{
Username.SendKeys(username);
Password.SendKeys(password);
Signin.Submit();
}
//...
}
}
和..
namespace UnitTestProject5
{
[Binding]
public class LoginTest
{
IWebDriver driver = null;
// constants con = new constants();
[Given(@"Go to website")]
public void GivenGoToWebsite()
{
driver =new FirefoxDriver();
driver.Navigate().GoToUrl("https://xero.com");
SignIn sin = new SignIn(driver);
PageFactory.InitElements(driver, sin);
sin.Clicklogin();
}
[Given(@"Enter user name & password")]
public void GivenEnterUserNamePassword()
{
sin.
}
[When(@"I press submit")]
public void WhenIPressSubmit()
{
Console.WriteLine("hello");
}
[Then(@"i should be my landing page")]
public void ThenIShouldBeMyLandingPage()
{
Console.WriteLine("hello");
}
}
}
功能/场景:
Feature: Successful Login
Scenario: Successful Login
Given Go to website
And Enter user name & password
When I press submit
Then i should be my landing page
答案 0 :(得分:2)
我相信你在每个给定的时间场景上下文之间丢失了变量。每个方法“Given-When-Then”都在静态上下文中执行,并且您在类中定义的任何变量在对它们的调用之间都会丢失。解决此问题的正确方法是使用 ScenarioContext 和 FeatureContext 对象。下面的伪示例:
:
[Given("Something nice")]
public void WhenIStartSomething()
{
// Add an inspector to the current context
var currentPageInspector = ScenarioContext.Current.Set("PageInspector", new PageInspector());
// Construct other stuff
ScenarioContext.Current.Add("signInInstance", SignIn(...));
}
[When("I do something planned")]
public void WhenIDoSomethingPlanned()
{
var signIn = ScenarioContext.Current.Get<SignIn>();
// do the action with signIn
}
[Then("I should see the following result")]
public void ThenIShouldSeeTheFollowingResult()
{
var currentPageInspector = ScenarioContext.Current.Get<PageInspector>();
currentPageInspector.CurrentPage.Title.ShouldEqual("My Landing Page");
}
你基本上做的是创建pageinspector和SignIn对象的静态实例,它们只作为它们运行的场景的一部分而存在。如果你有一个不同的场景,你重复任何步骤,那么scenariocontext将确保您为那里的对象提供不同的静态上下文。