How should I unit-test a simple CRUD-class?

前端 未结 2 1131
误落风尘
误落风尘 2021-02-04 18:28

I am right now trying to do very, very simple stuff with unit-testing in VS2008, to get started and get a feel for this. I think I have testing of small non-database stuff down,

相关标签:
2条回答
  • 2021-02-04 19:08

    I find that it works best to do basically what you've outlined. However, rather than splitting the create event up into each operation, I tend to create a single record in one method but store the id value of that record in a private class variable, then I fetch it back (read) inside of each method. So, then I have a Read assert method, then another Update assert method, and finally a Delete assert method.

    Though, what you've outlined above is very thorough. The biggest problem though, is if your delete method fails in your read assert method, then you could be mislead into believing that your read functionality is broken when in fact it is the delete functionality is deleted.

    0 讨论(0)
  • 2021-02-04 19:19

    I have been down this road and here are all of the problems you are going to run into:

    1) This looks good for one record, but what happens when you need 4 other records to create that record? You end up creating 4 records to test inserting your one record. This causes all of the following issues.

    2) Creating and deleting 4-5 records per test is slow, it will slowly add up and running your tests will take 45 minutes (trust me I was there). Slow tests mean you will never run them, which means they will be broken most of the time and useless.

    3) Your delete will fail for some missed foreign key relation or dependency and then trash data will be left in your database. This trash data will then cause other tests to fail.

    In light of this I would implore you to consider two things. The first is to try out using an ORM instead of writing all this logic yourself. Then you only need to test your mapping files (or even less depending on the ORM you use) or look into mocking so you can isolate the logic in your data access code from directly accessing the database.

    0 讨论(0)
提交回复
热议问题