Friday 9 September 2011

Exception thrown the first time an NUnit test that opens a SQL connection is run

When running an NUnit test that opens a SQL connection, the first time the test is run you may get an error similar to the following:

System.Data.SqlClient.SqlException : A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - The pipe is being closed.)

Running the test again then passes.

This can happen in this scenario: NUnit has run data access code, creating a connection, then SQL Server is restarted. If this is the case, the cause of the exception is as follows. If SQL Server is restarted after ADO.NET has built a connection using the same connection string as that used by the failing test, ADO.NET will attempt to reuse that connection from the connection pool without checking whether the connection is invalid. Because SQL Server has been restarted the connection is no longer valid and the exception is thrown.

To demonstrate this, restart SQL Server, then run the test. The test will fail. If the test is run again, it will pass. Next, close NUnit, then restart SQL Server and reopen NUnit (in either order) and rerun the test. The test will pass.

No comments:

Post a Comment