我遇到的問題是我有一堆從父類(BasePage)繼承的類(Pages)。任何時候我初始化一個子類,我還需要運行一個名爲WaitForLoadingToStop()的方法。我如何繼承這個方法並將其實現到我的子類的構造函數中?如何強制繼承類在其構造函數中實現方法?
這就是我需要改變的地方,因爲它被複制到所有的地方,所以我希望這個在創建類時自動被繼承和執行。
var assPage = new StudentAssesmentPage(Driver);
assPage.WaitForLoadingToStop();
這是一個示例子類,我有10人是這個樣子
public class StudentAssesmentPage : BasePage<StudentAssesmentPageObjectRepository>
{
public StudentAssesmentPage(IWebDriver driver) : base(driver, new StudentAssesmentPageObjectRepository(driver))
{}
}
下面是我BasePage類
public abstract class BasePage<TObjectRepository> where TObjectRepository : BasePageObjectRepository
{
protected WebDriverWait Wait { get; }
protected IWebDriver Driver { get; }
protected ApplicationUrls ApplicationUrls { get; }
public IJavaScriptExecutor JavascriptExecutor { get; }
protected Actions UserInteractions { get; private set; }
protected By _loadingSpinnerLocator = By.Id("spinner");
private readonly double LOADING_SPINNER_TIMEOUT = 60;
private TObjectRepository _objectRepository;
public BasePage(IWebDriver driver, TObjectRepository repository)
{
Driver = driver;
_objectRepository = repository;
UserInteractions = new Actions(Driver);
ApplicationUrls = new ApplicationUrls();
Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(GetPageTimeout()));
JavascriptExecutor = Driver as IJavaScriptExecutor;
}
internal TObjectRepository ObjectRepository
{
get { return _objectRepository; }
}
protected bool WaitForLoadingToStop(int secondsToSleep = 5)
{
var sleepTime = TimeSpan.FromSeconds(secondsToSleep);
Reporter.Debug($"{Helpers.GetCurrentMethodName()}. Going to sleep for:{sleepTime.Seconds}");
Thread.Sleep(sleepTime);
Reporter.Debug($"Now, going to wait for loading spinner for:{LOADING_SPINNER_TIMEOUT} seconds.");
var basePageWait = new WebDriverWait(Driver, TimeSpan.FromSeconds(LOADING_SPINNER_TIMEOUT));
basePageWait.Message =
$"Waited for {LOADING_SPINNER_TIMEOUT}sec for the spinner. However, it took longer than that for the application to load.";
return basePageWait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.XPath("//img[@src='/Content/images/spinner.gif']")));
}
}
混淆......'WaitForLoadingToStop'是基類的一部分,但你直接調用它,沒有上面示例中的實例。你的意思是'assPage.WaitForLoadingToStop()...'? –
哎呀,謝謝你指出。 –
你的問題沒有意義。 'WaitForLoadingToStop()'是'protected',但顯然是由聲明類之外的代碼調用的?無論如何,建設者花費時間是一個壞主意。處理冗長初始化的通常方法是編寫一個工廠方法。你可以在那裏等待,或者更好地使整個事情異步。至於你的問題到目前爲止,還不清楚它將如何工作,除了將該調用放入每個子類的構造函數之外。 –