单元测试插入/更新/删除 [英] Unit test insert/update/delete

查看:587
本文介绍了单元测试插入/更新/删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我GOOGLE了这一点,并没有真正找到我所需要的答案。

I have googled this a little and didn't really find the answer I needed.

我工作在C#中的网页与SQL Server和LINQ的客户。
我希望用户能够发送消息给对方。所以我要做的就是数据,我的单元测试这实际上进入数据库。

I am working on a webpage in C# with SQL Server and LINQ for a customer. I want the users to be able to send messages to each other. So what I do is that I unit test this with data that actually goes into the database.

问题是,我现在依赖于具有至少2的用户谁知道我的ID。此外,我有我的自我清理后。这导致了相当大的单元测试,在一个测试测试了很多东西。

The problem is that I now depend on having at least 2 users who I know the ID of. Furthermore I have to clean up after my self. This leads to rather large unit tests that test alot in one test.

可以说,我想更新的用户。这将意味着我将不得不ceate用户,更新它,然后将其删除。这是一个在一个单元测试很多断言,如果它失败更新我必须手动删除它。

Lets say I would like to update a user. That would mean that I would have to ceate the user, update it, and then delete it. This a lot of assertions in one unit test and if it fails with updating i have to manually delete it.

如果我会做任何其他方式,不保存数据到数据库,我不会肯定能够知道数据在数据库present更新等之后。

If I would do it any other way, without saving the data to DB, I would not for sure be able to know that the data was present in the database after updating etc.

什么是做到这一点,而无需一个测试,测试了很多功能在一个测试的正确方法?

What is the proper way to do this without having a test that tests a lot of functionality in one test?

推荐答案

是否所有考验的System.Transactions.TransactionScope块里面,根本就没有叫Scope.Complete()...所有的变化都将回滚当您退出,而其他用户将无法看到你在数据库中创建临时数据,所以测试过程只会影响试验机..

Do all the test inside of a System.Transactions.TransactionScope block, and simply do not call Scope.Complete() ... All changes will be rolled back when you exit, and other users will not be able to see the temporary data you create in the database, so the test process will only affect the test machine..

您可以输入一个新的用户,读取数据库,以验证它是否输入正确,你需要检查时,的TransactionScope块内任何其他...

You can enter a new user, read the database to verify that it was entered correctly, and whatever else you need to check, within the block of the TransactionScope...

有一个单元测试方法冒充两个不同的用户,全部在一个交易...

Have the single unit test method impersonate the two different users, all within the one transaction ...

例如。 code

   using (var scop = new System.Transactions.TransactionScope())
   {
       // all your test code and Asserts that access the database, 
       // writes and reads, from any class, ...
       // to commit at the very end of this block,
       // you would call
       // scop.Complete();  // ..... but don't and all will be rolled back
   }

这篇关于单元测试插入/更新/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆