使用 SpecFlow 和 Selenium 在 <td> 元素中获取文本

Getting text in <td> element using SpecFlow and Selenium

我在 SpecFlow 单元测试中遇到错误:

System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary. at TechTalk.SpecFlow.SpecFlowContext.Get[T](String key) at F*****.Live.PS.*******.Steps.*******.EnterStagingDateAndSaveSteps.ThenUserSeesInNEXTRE_ENROLMENTWINDOWTextFieldInPENSIONASSESSMENTDATESPageInPENSIONModule(String p0) in c:\Git\LivePeopleSystemTests\Fourth.Live.PS.AutomationTests\F*****.Live.PS.*******.Steps*******\EnterStagingDateAndSaveSteps.cs:line 175

这里是EnterStagingDateAndSaveSteps.cs

中引用的方法
[Then(@"user sees ""(.*)"" in NEXT RE-ENROLMENT WINDOW Text Field in PENSION ASSESSMENT DATES page in PENSION module")]
    public void ThenUserSeesInNEXTRE_ENROLMENTWINDOWTextFieldInPENSIONASSESSMENTDATESPageInPENSIONModule(string p0)
    {
        // GetNextReEnrollmentWindow
        string validator =
            ScenarioContext.Current.Get<PensionAssessmentDates>("_nextReEnrollmentWindow")
                .GetNextReEnrollmentWindow();
        Assert.IsTrue(validator == p0);
    }

(我也试过里面的return Driver.WaitAndGetText(_nextReEnrollmentWindow);

所以看起来键_nextReEnrollmentWindow不存在,但是这里定义在PensionAssessmentDates.cs:

private readonly By _nextReEnrollmentWindow = By.Id("NextReEnrollmentWindow"); 

PensionAssessmentSteps设置成ScenarioContext.Current这样:

    [Then(@"user sees ""(.*)"" in NEXT RE-ENROLMENT WINDOW Text Field in PENSION ASSESSMENT DATES page in PENSION module")]
    public void ThenUserSeesInNEXTRE_ENROLMENTWINDOWTextFieldInPENSIONASSESSMENTDATESPageInPENSIONModule(string p0)
    {
        // GetNextReEnrollmentWindow
        string validator =
            ScenarioContext.Current.Get<PensionAssessmentDates>("_nextReEnrollmentWindow")
                .GetNextReEnrollmentWindow();
        Assert.IsTrue(validator == p0);
    }

这是我尝试测试的实际网页,显示该元素存在:

对于我遗漏的导致我的单元测试停止的任何指示或建议,我将不胜感激:

 EnterStagingDateAndSaveSteps.WhenUserClicksSAVEButtonUnderAUTOMATICENROLMENTATSTAGINGDATEFrameInPENSIONASSESSMENTDATESPageInPENSIONModule() (0.7s)
Then user sees "02 Oct 2019 to 02 Apr 2020" in NEXT RE-ENROLMENT WINDOW Text Field in PENSION ASSESSMENT DATES page in PENSION module
-> error: The given key was not present in the dictionary.

ScenarioContext.Current.GetSet 方法仅允许您使用键将对象添加到附加到当前场景的值字典中。

在一步中将元素添加到字典后,您可以在另一步中检索它。您得到的异常意味着您没有使用键 _nextReEnrollmentWindow.

向字典中添加任何内容

您是否在代码中的任何地方调用了 ScenarioContext.Current.Set("_nextReEnrollmentWindow", something);?我怀疑不是。

鉴于您提出问题的方式,我怀疑您希望 ScenarioContext.Current.Get<PensionAssessmentDates>("_nextReEnrollmentWindow") 调用为您获取类型为 PensionAssessmentDates 的页面对象的当前实例,然后使用选择器 _nextReEnrollmentWindow。这不是它的工作方式。

你想做我相信的两件事之一。将您的页面对象 PensionAssessmentDates 添加到 ScenarioContext.Current,然后取出页面对象并调用使用私有字段 _nextReEnrollmentWindow.

的方法

或者(我认为更好)完全放弃对 ScenarioContext.Current 的使用,而是创建包含页面对象的对象并让 Specflows internal DI framework provide those to your step classes using context injection.