2017-04-21 32 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