How do I unit test persistence?

后端 未结 10 1273
长发绾君心
长发绾君心 2020-12-23 16:29

As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database.

I know that technically this would

相关标签:
10条回答
  • 2020-12-23 16:48

    Technically unit tests of persistance are not unit tests. They are integration tests.

    With C# using mbUnit, you simply use the SqlRestoreInfo and RollBack attributes:

        [TestFixture]
        [SqlRestoreInfo(<connectionsting>, <name>,<backupLocation>]
        public class Tests
        {
          
            [SetUp]
            public void Setup()
            {
            
            }
    
            [Test]
            [RollBack]
            public void TEST()
            {
               //test insert. 
            }
        }
    

    The same can be done in NUnit, except the attribute names differ slightly.

    As for checking, if your query iss successful, you normally need to follow it with a second query to see if the database has been changed as you expected.

    0 讨论(0)
  • 2020-12-23 16:49

    As Mike Stone said, DbUnit is great for getting the database into a known state before running your tests. When your tests are finished, DbUnit can put the database back into the state it was in before you ran the tests.

    DbUnit (Java)

    DbUnit.NET

    0 讨论(0)
  • 2020-12-23 16:49

    For NHibernate, I'd definitely advocate just mocking out the NHibernate API for unit tests -- trust the library to do the right thing. If you want to ensure that the data actually goes to the DB, do an integration test.

    0 讨论(0)
  • 2020-12-23 16:51

    You do the unit testing by mocking out the database connection. This way, you can build scenarios where specific queries in the flow of a method call succeed or fail. I usually build my mock expectations so that the actual query text is ignored, because I really want to test the fault tolerance of the method and how it handles itself -- the specifics of the SQL are irrelevant to that end.

    Obviously this means your test won't actually verify that the method works, because the SQL may be wrong. This is where integration tests kick in. For that, I expect someone else will have a more thorough answer, as I'm just beginning to get to grips with those myself.

    0 讨论(0)
  • 2020-12-23 16:51

    I usually create a repository, use that to save my entity and retrieve a fresh one. Then I assert that the retrieved is equal to the saved.

    0 讨论(0)
  • 2020-12-23 16:53

    I have written a post here concerning unit testing the data layer which covers this exact problem. Apologies for the (shameful) plug, but the article is too long to post here.

    I hope that helps you - it has worked very well for me over the last 6 months on 3 active projects.

    Regards,

    Rob G

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