2017-04-21 29 views
1

如果在執行打印操作後屏幕上出現錯誤,我需要測試失敗。硒測試。簡單的例外,如果在屏幕上出現錯誤

目前,該代碼工作:

[TestMethod] 
    [Description("Should Print")] 
    public void PrintDetails() 
    { 
     mainPage.PrintDetails(driver); 
     Thread.Sleep(300); 
     Wait.WaitForNoErrorMsg(driver); 
    } 

-

public static void WaitForNoErrorMsg(IWebDriver driver) 
     { 
      string errorMsg = "//div[@class='errorMessage']"; 
      try 
      { 
       WaitForElementNotVisible(driver, errorMsg, 3); 
      } 
      catch (Exception) 
      { 
       throw; 
      } 
     } 

-

public static void WaitForElementNotVisible(IWebDriver driver, string locator, int seconds) 
    { 
     WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds)); 
     wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.XPath(locator))); 
    } 

我覺得這不是一個最佳的方式,它可以用做更好的ExpectedException。我對嗎? 你能舉個例子嗎?

回答

0

您可以輕鬆地進行以下更改做到這一點:

[TestMethod] 
[Description("Should Print")] 
[ExpectedException(typeof(ApplicationException))] 
public void PrintDetails() 

和:

public static void WaitForNoErrorMsg(IWebDriver driver) 
     { 
      string errorMsg = "//div[@class='errorMessage']"; 
      try 
      { 
       WaitForElementNotVisible(driver, errorMsg, 3); 
      } 
      catch (Exception) 
      { 
       throw new ApplicationException(); 
      } 
     } 

這將完成爲您的測試將期待一個異常被拋出,只會傳球的時候預期的異常被拋出。

我不會這樣做。相反,我會創建兩個測試,一個用於測試正確的路徑,另一個用於檢查不良情況。

在這兩個測試中,我也會跳過使用異常,因爲它們不是必需的,您可以通過不使用它們來簡化它。

我會改變WaitForNoErrorMsgVerifyNoErrorMsg並讓它返回一個布爾值:

public static bool WaitForNoErrorMsg(IWebDriver driver) 
     { 
      string errorMsg = "//div[@class='errorMessage']"; 
      try 
      { 
       WaitForElementNotVisible(driver, errorMsg, 3); 
      } 
      catch (Exception) 
      { 
       return false; 
      } 

      return true; 
     } 

,有你的測試是這樣的:

[TestMethod] 
[Description("Should Print")] 
public void PrintDetailsSuccess() 
{ 
    mainPage.PrintDetails(driver); 
    Thread.Sleep(300); 
    bool errorMessagePresent = WaitForNoErrorMsg(driver); 
    Assert.IsFalse(errorMessagePresent); 
} 
+0

非常感謝!該解決方案正在工作。糾正我,如果我錯了,但我想,「errorMessagePresent」應重新命名爲「errorMessageAbsent」,因爲我們等待(驗證),將不會有錯誤。最後一行代碼應該像Assert.IsTrue(errorMessageAbsent); –

+0

@NikolayM好吧,這取決於你是否想測試以檢查錯誤是否存在或它是否存在。我會做兩個測試。在第一個饋送正常輸入中,驗證是否缺少錯誤消息,並在第二個饋送錯誤輸入中驗證是否存在錯誤消息。 – Gilles