<p>This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit testing was one of the requirements.  I ran into some trouble when I tried to test against the database.  To my understanding, unit tests should be:</p>

<ul>
<li>stateless</li>
<li>independent from each other</li>
<li>repeatable with the same results i.e. no persisting changes</li>
</ul>

<p>These requirements seem to be at odds with each other when developing for a database.  For example, I can't test Insert() without making sure the rows to be inserted aren't there yet, thus I need to call the Delete() first.  But, what if they aren't already there?  Then I would need to call the Exists() function first.</p>

<p>My eventual solution involved very large setup functions (yuck!) and an empty test case which would run first and indicate that the setup ran without problems.  This is sacrificing on the independence of the tests while maintaining their statelessness.</p>

<p>Another solution I found is to wrap the function calls in a transaction which can be easily rolled back, like <a href="http://weblogs.asp.net/rosherove/archive/2004/10/05/238201.aspx" rel="noreferrer">Roy Osherove's XtUnit</a>.  This work, but it involves another library, another dependency, and it seems a little too heavy of a solution for the problem at hand.</p>

<p>So, what has the SO community done when confronted with this situation?</p>

<hr>

<p>tgmdbm said:</p>

<blockquote>
  <p>You typically use your favourite
  automated unit testing framework to
  perform integration tests, which is
  why some people get confused, but they
  don't follow the same rules. You are
  allowed to involve the concrete
  implementation of many of your classes
  (because they've been unit tested).
  You are testing <strong>how your concrete
  classes interact with each other and
  with the database</strong>.</p>
</blockquote>

<p>So if I read this correctly, there is really no way to <em>effectively</em> unit-test a Data Access Layer.  Or, would a "unit test" of a Data Access Layer involve testing, say, the SQL/commands generated by the classes, independent of actual interaction with the database?</p>

[{'answer_id': 21603, 'author': 'tgmdbm', 'author_id': 1851, 'author_profile': 'https://Stackoverflow.com/users/1851', 'pm_score': 6, 'selected': True, 'text': "<p>There's no real way to unit test a database other than asserting that the tables exist, contain the expected columns, and have the appropriate constraints. But that's usually not really worth doing.</p>\n\n<p>You don't typically <strong>unit</strong> test the database. You usually involve the database in <strong>integration</strong> tests.</p>\n\n<p>You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database.</p>\n"}, {'answer_id': 21606, 'author': 'Gap_Tooth', 'author_id': 2223, 'author_profile': 'https://Stackoverflow.com/users/2223', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://dbunit.sourceforge.net/" rel="noreferrer">DBunit</a></p>\n\n<p>You can use this tool to export the state of a database at a given time, and then when you\'re unit testing, it can be rolled back to its previous state automatically at the beginning of the tests.  We use it quite often where I work.</p>\n'}, {'answer_id': 21608, 'author': 'Wing', 'author_id': 958, 'author_profile': 'https://Stackoverflow.com/users/958', 'pm_score': 3, 'selected': False, 'text': '<p>The usual solution to external dependencies in unit tests is to use mock objects - which is to say, libraries that mimic the behavior of the real ones against which you are testing.  This is not always straightforward, and sometimes requires some ingenuity, but there are several good (freeware) mock libraries out there for .Net if you don\'t want to "roll your own".  Two come to mind immediately:</p>\n\n<p><a href="http://www.ayende.com/" rel="noreferrer">Rhino Mocks</a> is one that has a pretty good reputation.</p>\n\n<p><a href="http://www.nmock.org/" rel="noreferrer">NMock</a> is another.</p>\n\n<p>There are plenty of commercial mock libraries available, too.  Part of writing good unit tests is actually desinging your code for them - for example, by using interfaces where it makes sense, so that you can "mock" a dependent object by implmenting a "fake" version of its interface that nonetheless behaves in a predictable way, for testing purposes.</p>\n\n<p>In database mocks, this means "mocking" your own DB access layer with objects that return made up table, row, or dataset objects for your unit tests to deal with.  </p>\n\n<p>Where I work, we typically make our own mock libs from scratch, but that doesn\'t mean you have to. </p>\n'}, {'answer_id': 21609, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 1, 'selected': False, 'text': "<p>What you should do is run your tests from a blank copy of the database that you generate from a script.  You can run your tests and then analyze the data to make sure it has exactly what it should after your tests run.  Then you just delete the database, since it's a throwaway.  This can all be automated, and can be considered an atomic action.</p>\n"}, {'answer_id': 21619, 'author': 'tgmdbm', 'author_id': 1851, 'author_profile': 'https://Stackoverflow.com/users/1851', 'pm_score': 2, 'selected': False, 'text': '<p>Yeah, you should refactor your code to access Repositories and Services which access the database and you can then mock or stub those objects so that the object under test never touches the database. This is much faster than storing the state of the database and resetting it after every test!</p>\n\n<p>I highly recommend <a href="http://code.google.com/p/moq/" rel="nofollow noreferrer">Moq</a> as your mocking framework. I\'ve used Rhino Mocks and NMock. Moq was so simple and solved all the problems I had with the other frameworks.</p>\n'}, {'answer_id': 370998, 'author': 'Aaron Powell', 'author_id': 11388, 'author_profile': 'https://Stackoverflow.com/users/11388', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re using LINQ to SQL as the ORM then you can generate the database on-the-fly (provided that you have enough access from the account used for the unit testing). See <a href="http://www.aaron-powell.com/blog.aspx?id=1125" rel="nofollow noreferrer">http://www.aaron-powell.com/blog.aspx?id=1125</a></p>\n'}, {'answer_id': 512161, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve had the same question and have come to the same basic conclusions as the other answerers here:  Don\'t bother unit testing the actual db communication layer, but if you want to unit test your Model functions (to ensure they\'re pulling data properly, formatting it properly, etc.), use some kind of dummy data source and setup tests to verify the data being retrieved.</p>\n\n<p>I too find the bare-bones definition of unit testing to be a poor fit for a lot of web development activities.  But this page describes some more \'advanced\' unit testing models and may help to inspire some ideas for applying unit testing in various situations:</p>\n\n<p><a href="http://www.marcclifton.com/tabid/87/Default.aspx" rel="nofollow noreferrer">Unit Test Patterns</a></p>\n'}, {'answer_id': 512190, 'author': 'Toran Billups', 'author_id': 2701, 'author_profile': 'https://Stackoverflow.com/users/2701', 'pm_score': 2, 'selected': False, 'text': '<p>I explained a technique that I have been using for this very situation <a href="https://stackoverflow.com/questions/12374/has-anyone-had-any-success-in-unit-testing-sql-stored-procedures/25204#25204">here</a>.</p>\n\n<p>The basic idea is to exercise each method in your DAL - assert your results - and when each test is complete, rollback so your database is clean (no junk/test data).</p>\n\n<p>The only issue that you might not find "great" is that i typically do an entire CRUD test (not pure from the unit testing perspective) but this integration test allows you to see your CRUD + mapping code in action.  This way if it breaks you will know before you fire up the application (saves me a ton of work when I\'m trying to go fast)</p>\n'}, {'answer_id': 23297120, 'author': 'Mustafa Ekici', 'author_id': 687817, 'author_profile': 'https://Stackoverflow.com/users/687817', 'pm_score': 1, 'selected': False, 'text': '<p>Testing the data layer and the database together leaves few surprises for later in the\nproject. But testing against the database has its problems, the main one being that\nyou’re testing against state shared by many tests. If you insert a line into the database\nin one test, the next test can see that line as well.<br>\nWhat you need is a way to roll back the changes you make to the database.<br>\nThe <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx" rel="nofollow">TransactionScope</a> class is smart enough to handle very complicated transactions,\nas well as nested transactions where your code under test calls commits on its own\nlocal transaction.\nHere’s a simple piece of code that shows how easy it is to add rollback ability to\nyour tests: <br></p>\n\n<pre><code>    [TestFixture]\n    public class TrannsactionScopeTests\n    {\n        private TransactionScope trans = null;\n\n        [SetUp]\n        public void SetUp()\n        {\n            trans = new TransactionScope(TransactionScopeOption.Required);\n        }\n\n        [TearDown]\n        public void TearDown()\n        {\n            trans.Dispose();\n        }\n\n        [Test]\n        public void TestServicedSameTransaction()\n        {\n            MySimpleClass c = new MySimpleClass();\n            long id = c.InsertCategoryStandard("whatever");\n            long id2 = c.InsertCategoryStandard("whatever");\n            Console.WriteLine("Got id of " + id);\n            Console.WriteLine("Got id of " + id2);\n            Assert.AreNotEqual(id, id2);\n        }\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/21583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1266/']