What is the best way to test a stored procedure?

前端 未结 4 1603
悲哀的现实
悲哀的现实 2021-02-12 02:39

Like many companies that require all access be through stored procedures, we seem to have a lot of business logic locked away in sprocs. These things are just plain hard to tes

相关标签:
4条回答
  • 2021-02-12 03:14

    One method that I've used is to write a 'temporary' unit test for refactoring a particular stored procedure. You save the data from a set of queries from a database, and store them somewhere where a unit test can get at them.

    Then, refactor your proc stock. The data returned should be the same, and can be compared directly against the saved data, automatically or manually.

    An alternative is to run the two stored procedures in parallel, and compare the result sets.

    This works particularly well for select-only stored procedures, but updates, inserts & deletes are more complex.

    I've used this method to get the code to a state where it is more susceptible to unit testing, or simpler, or both.

    0 讨论(0)
  • 2021-02-12 03:16

    Not sure if this is what you're looking for, but since you're using SQL Server: I've found LINQ to be a great tool test stored procs. You can just drag the stored procedures onto a DBML diagram and then call them as methods on your datacontext. Beats setting up ADO connections etc for a test harness. If you set up a test project in Visual Studio for example, you can simply test your procedures like methods on another object. If your stored procs return result sets, I think LINQ will translate that into anonymous variables that you should be able to access via IEnumerable or IQueryable (somebody pls verify this). But if you're returning return codes only, this should be a quick and fairly easy way.

    0 讨论(0)
  • 2021-02-12 03:19

    A colleague swears by the TSQLUnit testing framework. May be worth a look for your needs.

    0 讨论(0)
  • 2021-02-12 03:29

    We had a very thin Data Access layer which basically facaded stored procedures to look like C# methods. Our NUnit test-suite then had SetUp/TearDown to create/rollback a transaction and test methods that called into DAL. Nothing fancy, and proved to be easier to maintain than TSQLUnit test-suite.

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