[英]Best way to Unit test non-existing Database
We have a build server which does not have a database running on its machine. 我们有一个构建服务器,它的计算机上没有运行数据库。 Now we want to make unit tests which also cover SQL-related tasks, for example writing mock-data and reading them again to verify the output (it gets manipulated by C# code in the process).
现在,我们要进行单元测试,其中还涉及与SQL有关的任务,例如编写模拟数据并再次读取它们以验证输出(该过程在过程中由C#代码操纵)。
So the common approach would be to provide a connection-string to the remote server which actually runs a database. 因此,通常的方法是为实际运行数据库的远程服务器提供连接字符串。 This works, but it is unwanted because the database-server could be inaccessible when the build is triggered, and therefore the automatic tests would fail .
这可以工作,但是这是不希望的,因为触发构建时可能无法访问数据库服务器,因此自动测试将失败 。
What is the best way to create a "pseudo-database" while running Unit tests? 在运行单元测试时创建“伪数据库”的最佳方法是什么? Is this even possible without an actual database?
如果没有实际的数据库,这甚至可能吗? Does it even make sense?
有道理吗?
Use mocking framework like Moq
, check here . 使用
Moq
类的Moq
框架,请在此处检查。 That is the exact purpose of the Mocking frameworks that only a given component can be unit tested and any integration like database can be mocked to return the valid pre-defined result at the run-time and thus determine the working of given code / unit 这就是Mocking框架的确切目的,即只能对给定的组件进行单元测试,并且可以模拟任何集成(如数据库)以在运行时返回有效的预定义结果,从而确定给定代码/单元的工作方式
The commonly accepted answer to "how do I unit test something with external dependencies" is to use a mocking layer. 关于“如何使用外部依赖项对单元进行单元测试”的公认答案是使用模拟层。
However, that very quickly becomes unwieldy - you end up writing and maintaining a lot of code just to mimic your database, and it's not clear this code will pay for itself. 但是,这很快变得很笨拙-您最终只是为了模仿数据库而编写并维护了大量代码,并且尚不清楚该代码是否能为自己带来回报。 For instance, if your SQL statements has a typo, your unit tests won't catch that.
例如,如果您的SQL语句有错别字,则单元测试将无法捕获错字。
Instead, it is much better to factor the code which manipulates the data out into a layer which can be unit-tested without database access. 取而代之的是,将处理数据的代码分解为一层,而无需数据库访问即可进行单元测试,这要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.