Re: C# .NET: Can't run sequential tests in same project

430 views
Skip to first unread message
Message has been deleted
Message has been deleted
Message has been deleted

Magesh N

unread,
Mar 22, 2018, 12:44:05 AM3/22/18
to Selenium Users
Does the first test's browser has closed in Teardown method?

In the stack trace, it is mentioned as a problem while executing the methods in TearDown

TearDown : OpenQA.Selenium.WebDriverException : Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:56114

On Wednesday, March 21, 2018 at 10:28:19 PM UTC+5:30, Roger Cook wrote:
Hello.. 

I've got a situation where I have many tests within one C# .NET project, but for some reason, I can't run more than one at a time. If I try running tests from different projects, it works. 

I'm using NUnit to control my test executions. I've opened this project as a Class Library. I've used the framework that's outlined at http://toolsqa.com/selenium-c-sharp/.

Here's the error I get: 

Test Name: <TestName>
Test FullName: <Test Full Name>
Test Source: C:\Users\roger.cook\Code\<Path>\<File>.cs : line 81
Test Outcome: Failed
Test Duration: 0:00:08.2
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByCssSelector(String cssSelector)
   at OpenQA.Selenium.By.<>c__DisplayClass23_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
   at OpenQA.Selenium.Support.PageObjects.DefaultElementLocator.LocateElement(IEnumerable`1 bys)
   at OpenQA.Selenium.Support.PageObjects.WebElementProxy.get_Element()
   at OpenQA.Selenium.Support.PageObjects.WebElementProxy.Invoke(IMessage msg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at OpenQA.Selenium.IWebElement.get_Displayed()
   at OpenQA.Selenium.Support.UI.ExpectedConditions.<>c__DisplayClass20_0.<ElementToBeClickable>b__0(IWebDriver driver)
   at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
   at NWSAutomatedTests.Common.PageObjects.LoginPage201708.AzureActiveDirectoryLogin() in C:\Users\roger.cook\Code\NICServices\NWSAutomatedTests\NWSAutomatedTests\PageObjects\LoginPage201708.cs:line 50
   at NWSAutomatedTests.APIVault.TestCases.APIVaultRegressionTests.APITestSetup() in C:\Users\roger.cook\Code\NICServices\NWSAutomatedTests\APIVault\TestCases\APIVaultRegressionTests.cs:line 25
--TearDown
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at NWSAutomatedTests.Common.Extensions.DriverExtensions.WaitForDocumentReady(IWebDriver driver) in C:\Users\roger.cook\Code\NICServices\NWSAutomatedTests\NWSAutomatedTests\Extensions\DriverExtensions.cs:line 33
   at NWSAutomatedTests.APIVault.PageObjects.APIVaultMenuBar.ClickLogout() in C:\Users\roger.cook\Code\NICServices\NWSAutomatedTests\APIVault\PageObjects\APIVaultMenuBar.cs:line 63
   at NWSAutomatedTests.APIVault.TestCases.APIVaultRegressionTests.APITestTearDown() in C:\Users\roger.cook\Code\NICServices\NWSAutomatedTests\APIVault\TestCases\APIVaultRegressionTests.cs:line 34
Result Message:
OpenQA.Selenium.WebDriverException : Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:56114
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.MakeHttpRequest(HttpRequestInfo requestInfo)
   at OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
TearDown : OpenQA.Selenium.WebDriverException : Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:56114
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.MakeHttpRequest(HttpRequestInfo requestInfo)
   at OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
Result StandardOutput:
Begin API Vault Test Setup
Begin API Vault Test Teardown
Waiting for five instances of document.readyState returning 'complete' at 100ms intervals.

Here are the setup and teardown methods I use: 

        [SetUp]
       
public void Setup()
       
{
           
Console.WriteLine("Begin Test Setup");
           
BrowserFactory.InitBrowser(Common.Properties.Settings.Default.BrowserString);
           
BrowserFactory.LoadApplication(Properties.Settings.Default.Url);
           
CommonPage.Login201708.AzureActiveDirectoryLogin();
           
Assert.That(BrowserFactory.Driver.Url.ToLower(), Is.EqualTo(Properties.Settings.Default.Url.ToLower()));
           
Console.WriteLine("End Test Setup");
       
}


       
[TearDown]
       
public void TearDown()
       
{
           
Console.WriteLine("Begin Test Teardown");
           
Page.Menu.ClickLogout();
           
Assert.That(BrowserFactory.Driver.Url.ToLower(), Does.Contain("login.microsoftonline.com"));
           
BrowserFactory.CloseAllDrivers();
           
Console.WriteLine("End API Vault Test Teardown");
       
}


And here are the methods in the Browser Factory that I call for these: 

        public static void InitBrowser(string browserName)
       
{
           
switch (browserName)
           
{
               
case "Firefox":
                   
if (driver == null)
                   
{
                        driver
= new FirefoxDriver();
                        driver
.Manage().Window.Maximize();
                        wait
= new WebDriverWait(driver, TimeSpan.FromSeconds(Properties.Settings.Default.DefaultTimeout));
                       
Drivers.Add("Firefox", driver);
                       
Waits.Add("Firefox", wait);
                   
}
                   
break;
               
case "IE":
                   
if (driver == null)
                   
{
                        driver
= new InternetExplorerDriver();
                        driver
.Manage().Window.Maximize();
                        wait
= new WebDriverWait(driver, TimeSpan.FromSeconds(Properties.Settings.Default.DefaultTimeout));
                       
Drivers.Add("IE", driver);
                       
Waits.Add("IE", wait);
                   
}
                   
break;
               
case "Chrome":
                   
if (driver == null)
                   
{
                       
ChromeOptions opts = new ChromeOptions();
                        opts
.AddArgument("ignore-certificate-errors");
                        opts
.AddArgument("start-maximized");
                        opts
.AddUserProfilePreference("credentials_enable_service", false);
                        opts
.AddUserProfilePreference("profile.password_manager_enabled", false);
                       
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
                        driver
= new ChromeDriver(service, opts, TimeSpan.FromMinutes(2));
                        wait
= new WebDriverWait(driver, TimeSpan.FromSeconds(Properties.Settings.Default.DefaultTimeout));
                       
Drivers.Add("Chrome", driver);
                       
Waits.Add("Chrome", wait);
                   
}
                   
break;
               
case "Chrome-headless":
                   
if (driver == null)
                   
{
                       
ChromeOptions opts = new ChromeOptions();
                        opts
.AddArgument("ignore-certificate-errors");
                        opts
.AddArgument("headless");
                        opts
.AddUserProfilePreference("credentials_enable_service", false);
                        opts
.AddUserProfilePreference("profile.password_manager_enabled", false);
                       
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
                        driver
= new ChromeDriver(service, opts, TimeSpan.FromMinutes(2));
                        wait
= new WebDriverWait(driver, TimeSpan.FromSeconds(Properties.Settings.Default.DefaultTimeout));
                       
Drivers.Add("Chrome", driver);
                       
Waits.Add("Chrome", wait);
                   
}
                   
break;
               
case "Edge":
                   
if (driver == null)
                   
{
                        driver
= new EdgeDriver();
                        driver
.Manage().Window.Maximize();
                        wait
= new WebDriverWait(driver, TimeSpan.FromSeconds(Properties.Settings.Default.DefaultTimeout));
                       
Drivers.Add("Edge", driver);
                       
Waits.Add("Edge", wait);
                   
}
                   
break;
           
}
       
}


       
public static void LoadApplication(string url)
       
{
           
Driver.Url = url;
       
}


       
public static void CloseAllDrivers()
       
{
           
foreach (var key in Drivers.Keys)
           
{
               
Waits[key] = null;
               
Drivers[key].Close();
               
Drivers[key].Quit();
               
// Drivers[key].Dispose();
                GC
.Collect();
           
}
       
}

My intent is to start up a clean browser for each test. That is: 

  1. Start the WebDriver and browser.
  2. Navigate to the application under test (which redirects to a Microsoft Azure Active Directory web login).
  3. Login using Microsoft AAD (which navigates back to the application under test when successful).
  4. Perform the test.
  5. Close the browser and WebDriver.
Then repeat the whole thing for the next test. 

The first test passes with flying colors, but the second test looks like it can't find the driver, even though I think I'm telling it to start up a new instance for the new test. Using different browsers doesn't matter.

Thanks for your help!

roger

Roger Cook

unread,
Mar 22, 2018, 1:41:09 AM3/22/18
to Selenium Users
Yes, the first browser closes,but the first test passes. The failure is noted on the second test.

Magesh N

unread,
Mar 22, 2018, 5:43:27 AM3/22/18
to Selenium Users
Which browser have you mentioned for Test_1 and Test_2?

Roger Cook

unread,
Mar 22, 2018, 12:02:09 PM3/22/18
to Selenium Users
Chrome, but the same thing happens with other browsers as well.

Magesh N

unread,
Mar 27, 2018, 3:25:48 AM3/27/18
to Selenium Users
Can you add your Browser Factory file here
Message has been deleted

Roger Cook

unread,
Mar 27, 2018, 11:09:40 AM3/27/18
to Selenium Users
Hopefully this only comes through once.

roger
BrowserFactory.cs

Roger Cook

unread,
Apr 17, 2018, 8:48:06 PM4/17/18
to Selenium Users
The BrowserFactory initialized the private driver, but it never let it go.

As part of the CloseAllDrivers() method, I added this line:
driver = null;
which eliminated the reference to the current driver. With that, the driver was fully closed and dereferenced, and when I tried to start up a new one, it was able to start. I can finally run more than one test in the same project.

jsol...@ifscompanies.com

unread,
Jan 8, 2019, 11:51:39 PM1/8/19
to Selenium Users

Hi Roger,  I am new to Selenium and am running into the same issue you mentioned above.   I am hoping to get some guidance.    Please response if you receive this note.  thank you.   

Roger Cook

unread,
Jan 9, 2019, 2:06:09 AM1/9/19
to seleniu...@googlegroups.com
Make sure to close down (Driver.close();) and then null out (Driver = null;) at the end of each test.

Roger 

On Tue, Jan 8, 2019, 10:51 PM <jsol...@ifscompanies.com wrote:

Hi Roger,  I am new to Selenium and am running into the same issue you mentioned above.   I am hoping to get some guidance.    Please response if you receive this note.  thank you.   

--
You received this message because you are subscribed to a topic in the Google Groups "Selenium Users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/selenium-users/xHtN5zwWOwo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to selenium-user...@googlegroups.com.
To post to this group, send email to seleniu...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/selenium-users/b4a0d655-237d-4ded-a6c0-db12a3f91aea%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

jsol...@ifscompanies.com

unread,
Jan 10, 2019, 12:08:51 PM1/10/19
to Selenium Users
Thank you.  It was actually a different problem...  newbie mistake.  :)  I have it working now.  

Roger Cook

unread,
Jan 10, 2019, 3:22:48 PM1/10/19
to seleniu...@googlegroups.com
Show your code to help others? 

jsol...@ifscompanies.com

unread,
Jan 29, 2019, 2:42:21 PM1/29/19
to Selenium Users
Hi Roger, 

Finally getting my 'fix' shared with you.

I added to the Close method, Waits.Clear() and Drivers.Clear().  The Waits[key] = null and Drivers[key].Quit were not completely cleared.  Anyway, no more lingering open browser windows.  

The Close method code:
        public static void Close()
        {

            foreach (var key in Drivers.Keys)
            {
                
                Waits[key] = null;
                Drivers[key].Quit();

                driver = null;


                GC.Collect();
                Console.WriteLine("here");

            }


            Waits.Clear();
            Drivers.Clear();

        }

zeon

unread,
Jul 26, 2019, 10:41:21 PM7/26/19
to Selenium Users
Hi everyone,

How did you get the Waits[key] recognized?  I always get Waits does not exist in the current context?  I see awaits but that does not compile.    I didn't use Waits[...] and it seem to work too.

Thanks again

Steve
Reply all
Reply to author
Forward
0 new messages