问题描述
我正在尝试为连接到 SQL Server 以实现持久性的代码编写一些单元测试,但我希望能够通过将其指向 SQL Server 实例来运行我的单元测试,并让测试创建他们自己的数据库来运行测试,所以在每次测试之后,它可以删除数据库,然后在下一次测试之前重新创建它,所以我知道没有遗留数据或结构遗留下来影响下一次测试.
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.
推荐答案
简而言之:不,你不能那样做.您可能可以从连接字符串中省略数据库,但在这种情况下,该连接将建立到连接到 SQL Server 的登录名的配置默认数据库(并且该默认数据库必须在建立连接时存在)
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
首先连接到您的实例和数据库
master
并创建新的testdb
(或任何名称)
first connect to your instance and database
master
and create your newtestdb
(or whatever it's called)
断开连接
在您的测试中,连接到实例和 testdb
数据库
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!
这篇关于是否可以在不指定数据库的情况下连接到 SQL Server?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!