我想在我的程序中运行多个[Test Method]。并希望在每次[测试方法]后关闭浏览器会话

时间:2017-11-09 17:36:24

标签: c# selenium selenium-webdriver mstest

请记住:我的测试通过时没有发现任何问题。测试失败时我看到了问题。

问题:我正在运行[Test Method] -1并为Test-1提供错误的Xpath来处理失败方案。

我的驱动程序一直在等待浏览器,因为XPath是错误的,但最后,它没有关闭浏览器会话。驱动程序在测试资源管理器上抛出失败状态。

我希望驱动程序关闭会话,无论测试是否因任何原因而失败。

TestClass.cs

我正在运行大量[Test Method]

[Test Method]
public void Test1()
{
    try{
        Assert.IsTrue(ProgramPage.checkTest1());
    }
    catch(Exception e)
    {
        throw ; 
    }
}


[Test Method]
public void Test2()
{
    try{
        Assert.IsTrue(ProgramPage.checkTest2());
    }
    catch(Exception e)
    {
        throw ; 
    }
}

ProgramPage.cs

我定义页面逻辑和页面对象

// can we put try and catch block on Assert ?? 
// it's simple display check example
public static class {

    public static IWebElement webElement = null ; 

    public static void checkTest1()
    {
        try {
            webElement = driver.FindElement(xpath--1);

            if(webElement.Displayed)
            {
                Console.Write("element is visible ");
            }
            else
            {
                Console.Write("element is not visible");
            }
        }

        catch(Exception e)
        {
            throw ;
        }
    }

    public static void checkTest2()
    {
        try {
            webElement = driver.FindElement(xpath--2);
            // SAY THIS XPATH is Wrong 

        if(webElement.Displayed)
        {
            Console.Write("element is visible ");
        }
        else
        {
            Console.Write("element is not visible");
        }
    }

    catch(Exception e)
    {
        throw ;
    }
}

// when test fail on wrong Xpath , driver does not close the Browser session 

Driver.cs

我初始化驱动程序并从此处关闭。

public static class{

    // I am not having private driver for each class , is that an issue ?
    [Test Initialize]
    public void  Init()
    {
        //initialize the driver 
        //launch and login the browser
    }


    [Test Cleanup]
    public void Close()
    {
        Driver.Close(); //  IT has to be executed no matter
        // what the test result is 
    }

} 

1 个答案:

答案 0 :(得分:1)

使类非静态,并编写不带空格的TestInitialize和TestCleanup。

示例:

public class BasicTestClass
{
    private IWebDriver driver;

    [TestInitialize]
    public void  Init()
    {
        driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://www.google.nl");
    }

    [TestCleanup]
    public void Close()
    {
        Driver.Close();
    }

    // TestMethods go here
} 

此外,将测试类放入名为Driver.cs

的文件中似乎很奇怪