I am wondering what the best way to structure context injection is. I know that page objects should be instantiated / disposed of as they are needed (don't initialize all page objs at the start of a test). I am wondering what the best way of passing a page object around between tests is.
Approach one:
Every time you navigate to the new page, just add it to the scenario context
[Given(@"I am on the homepage"]
public void GivenIAmOnTheHomepage(){
ScenarioContext.Current.Set(new Homepage().NavigateTo());
}
[Then(@"The homepage should have a banner"]
public void ThenTheHomepageShouldHaveABanner(){
var homepage = ScenarioContext.Current.Get<Homepage>();
Assert.IsTrue(homepage.BannerIsDisplayed());
}
Con:
If you navigate to another page, the homepage isn't disposed
[When(@"I click on the FAQ link")]
public void WhenIClickOnTheFAQLink(){
var homepage = ScenarioContext.Current.Get<Homepage>();
FAQPage FAQ = homepage.ClickFAQLink();
ScenarioContext.Current.Set(FAQ);
//homepage is not disposed, even though we are no longer on the homepage!
}
Approach two: Store the current page object using a key, use that key to access it every time
[Given(@"I am on the homepage"]
public void GivenIAmOnTheHomepage(){
ScenarioContext.Current.Set(new Homepage().NavigateTo(), "currentPage");
}
[Then(@"The homepage should have a banner"]
public void ThenTheHomepageShouldHaveABanner(){
var homepage = (Homepage)test["currentPage"];
Assert.IsTrue(homepage.BannerIsDisplayed());
}
[When(@"I click on the FAQ link")]
public void WhenIClickOnTheFAQLink(){
var homepage = (Homepage)test["currentPage"];
FAQPage FAQ = homepage.ClickFAQLink();
ScenarioContext.Current.Set(FAQ, "currentPage");
//homepage is disposed
}
Con:
This is more likely to have typos, and if I want to pass more than just page objects around (like the current customer that we are using, or a promotion code) the number of keys can add up and get confusing. Also, casting the current page every time you want to access it feels messy.
Anyone have any recommendations for this?