I want to write a unit-test which asserts a connection string is valid so that a conenction is established to a SQL Db.
if I have :
string connectionString = GetCOnenctionString();
bool conenctionEstablished = false;
How can I set 'conenctionEstablished' variable's value as a result of a check to a Db with the 'connectionSt开发者_StackOverflowring' provided?
So that I can use it in an Assert.
You could try to connect in a try/catch then set conenctionEstablished based on whether the connection succeeds or not.
It is not going to be a "pure" unit test because your database is real but any way. I would use a try catch block and after opening the connection execute a "select 1" statement with ExecuteNonQuery(). At the end of the try block set the flag to true.
There are different states available, look at this:
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
there is an Enumeration called Connectionstate so you can assert if the connection is closed, open connecting ,etc.
Assert.AreEqual(ConnectionState.Connecting, sqlcon.State);
We could rather check, if the connection is open or not, by using the following code:
using System.Data;
if (conn.State == ConnectionState.Open)
{
return true;
}
else
{
return false;
}
精彩评论