Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a connection to a Db is established successfully?

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 'connectionString' provided?

So that I can use it in an Assert.

like image 734
pencilCake Avatar asked Dec 11 '25 16:12

pencilCake


2 Answers

You could try to connect in a try/catch then set conenctionEstablished based on whether the connection succeeds or not.

like image 128
sproketboy Avatar answered Dec 14 '25 05:12

sproketboy


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.

like image 42
evpo Avatar answered Dec 14 '25 05:12

evpo