简体   繁体   English

单元测试C#数据库相关代码

[英]Unit testing C# database dependent code

I would like to create unit tests for data dependent code. 我想为数据相关代码创建单元测试。 For example: 例如:

A user class that has the usual create, update & delete. 具有通常的创建,更新和删除的用户类。

If I wanted to create a test for "user already exists" scenario, or and update or delete test. 如果我想为“用户已经存在”场景创建测试,或者更新或删除测试。 I would need to know that a specific user already exists in my database. 我需要知道数据库中已经存在特定用户。

In such cases, what would be the best approach to have stand alone tests for these operations that can run in any order? 在这种情况下,对可以按任何顺序运行的这些操作进行独立测试的最佳方法是什么?

When you have dependencies like this think about whether you want to be Integration Testing as opposed to Unit Testing. 当您具有这样的依赖关系时,请考虑是否要进行集成测试而不是单元测试。 If you do want to do Unit tests take a look at using Mock Data. 如果您确实想进行单元测试,请看一下使用模拟数据。

Integration Testing: Tests how you code integrates with different parts of a system. 集成测试:测试您的代码如何与系统的不同部分集成。 This can be making sure your code connects to a database properly or has created a file on the filesystem. 这可以确保您的代码正确连接到数据库或已在文件系统上创建了文件。 These tests are usually very straight-forward and do not have the same constraint of "being able to run in any order." 这些测试通常非常简单,并且没有“能够以任何顺序运行”的相同约束。 However, they require a specific configuration in order to pass which means they do float well from developer to developer. 但是,它们需要特定的配置才能通过,这意味着它们确实在开发人员之间浮动良好。

Unit Testing: Tests your code's ability to preform a function. 单元测试:测试代码执行功能的能力。 For example "Does my function AddTwoNumbers(int one, int two) actually add two numbers?" 例如“我的函数AddTwoNumbers(int one, int two)实际上加了两个数字吗?” Unit tests are to ensure any changes in code does not effect the expected results. 单元测试是为了确保代码中的任何更改都不会影响预期的结果。

When getting into areas like "Does my code call the database any enter the result correctly?" 当进入“我的代码是否调用数据库是否正确输入结果?”之类的区域时, you need to consider that unit tests are not meant to interact with the system. 您需要考虑单元测试并非旨在与系统交互。 This is where we get into using "mock data." 这就是我们使用“模拟数据”的地方。 Mock classes and mock data take the place of an actual system to just ensure that your code "called out in the way we were expecting." 模拟类和模拟数据代替了实际的系统,只是确保您的代码“以我们期望的方式被调用”。 The difficult part about this is it can be done but most of the .Net Framework classes do not provide the needed Interfaces in order to do it easily. 困难的部分是可以做到的,但是大多数.Net Framework类都不提供轻松实现所需的接口。

See the MSDN page on Tesing for more info. 有关更多信息,请参见Tesing上MSDN页面 Also, consider this MSDN article on Mock Data. 另外,请考虑有关Mock Data的MSDN文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM