Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to connect to SQL Server without specifying a database?

I'm trying to write some unit tests for my code that connect to SQL Server for persistence, but I would like to be able to run my unit tests by just pointing it at a SQL Server instance, and let the tests create their own database to run tests in, so after each test it can just drop the database and then on setup before the next test recreate it, so I know there is no legacy data or structures left over from a previous test effecting the next test.

like image 690
Daniel Robinson Avatar asked Jan 10 '23 06:01

Daniel Robinson


1 Answers

In brief: no, you cannot do that. You might be able to leave out the database from the connection string, but in that case, that connection will be made to the configured default database of the login that's connecting to SQL Server (and that default database must exist at the time the connection is made)

If you want to have this scenario, you need to

  1. first connect to your instance and database master and create your new testdb (or whatever it's called)

  2. disconnect

  3. in your tests, connect to the instance and the testdb database

Better yet: use a mocking framework of some sort so you don't even need an actual database in your testing scenario!

like image 85
marc_s Avatar answered Jan 25 '23 20:01

marc_s