Automated Testing with Databases

4,421 views
4,166 views

Published on

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,421
On SlideShare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
Downloads
73
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide
  • Automated Testing with Databases

    1. 1. Automated Testing with Databases <ul><ul><li>Philip Nelson </li></ul></ul><ul><ul><li>Chief Scientist </li></ul></ul><ul><ul><li>Plan Administrators Inc. </li></ul></ul>
    2. 2. Contact <ul><li>The final version of slides and demo code will be available at my blog site, http://tinyurl.com/78zb2 </li></ul><ul><li>This presentation began as an article in “Applied Domain Driven Design and Patterns” by Jimmy Nilsson </li></ul><ul><li>XUnit patterns by Gerard Meszaros </li></ul>
    3. 3. Why?
    4. 4. What we'll cover <ul><li>What do I mean by automated tests? </li></ul><ul><li>When should you include database access in tests? </li></ul><ul><li>What alternatives are there? </li></ul><ul><li>How do you maintain test data? </li></ul><ul><li>How do test with changing database schemas? </li></ul>
    5. 5. What do I mean by automated tests? <ul><li>Tests are run by a process and the results are tallied automatically </li></ul><ul><li>Setup/cleanup for the tests do not require human intervention </li></ul><ul><li>Tool support for verification of results </li></ul><ul><li>Most commonly done with testing tools and frameworks, for example: junit, nunit, TestNG, AnyUnit etc. </li></ul>
    6. 6. When should you include database access in tests? <ul><li>Integration tests of course: you are integrating various parts of your system and the DB is important </li></ul><ul><li>What about unit tests? </li></ul><ul><li>What about acceptance tests, particularly the part of a plan where regression testing is executed? </li></ul>
    7. 7. When should you avoid databases in tests? <ul><li>Testing logic and design? </li></ul><ul><li>Running hundreds to thousands of tests? </li></ul><ul><li>Logic in SQL or Stored Procedures? </li></ul><ul><li>Database isolated by layers or tiers? </li></ul><ul><li>Data shared by many people? </li></ul>
    8. 8. How should you decide? <ul><li>There is no perfect answer </li></ul><ul><li>The basic trade off is test speed vs # of database accesses and resets </li></ul><ul><li>The more subtle trade off is between unit testing and integration testing </li></ul><ul><li>How do I know I'm done? </li></ul>
    9. 9. Test flow <ul><li>Establish preconditions </li></ul><ul><li>Execute code under test </li></ul><ul><li>Verify </li></ul><ul><li>Clean up </li></ul>
    10. 10. Test preconditions <ul><li>After 5 unsuccessful logins, the user will be locked out </li></ul><ul><li>When inventory has been depleted to the critical level, send a message to the order system to replenish </li></ul><ul><li>After assets have increased over $100,000 begin the process to have the account type changed to plan Y </li></ul><ul><li>Manual testing is really hard because the required conditions often happen only once </li></ul>
    11. 11. public void TestLoginFailCheck() { doLoginSetup(); //stuff to test ..... Assert.AreEqual(“what I expected”, theTestedThing, “not good”); doLoginCleanup(); } public void TestDepletedInventory() { doInventorySetup(); ..... Assert.AreEqual(“what I expected”, theTestedThing, “not good”); doInventoryCleanup(); }
    12. 12. public void resetEnvironment() { .... } //database and other shared setup public void TestLoginFailCheck() { doLoginSetup(); //stuff to test ..... Assert.AreEqual(“what I expected”, theTestedThing, “not good”); } public void TestDepletedInventory() { doInventorySetup(); ..... Assert.AreEqual(“what I expected”, theTestedThing, “not good”); }
    13. 13. Tests should only setup what is unique about the test <ul><li>Yes – previous number of failed logins </li></ul><ul><li>Yes – current inventory </li></ul><ul><li>Yes – current asset total values </li></ul><ul><li>No – test logins to work with </li></ul><ul><li>No – part numbers needed to fill out inventory </li></ul><ul><li>No – names of assets needed to make Asset class load correctly </li></ul>
    14. 14. Recap <ul><li>Automated testing allows you to think about setup for groups of tests with a shared setup </li></ul><ul><li>Groups of tests involving a database and a deep class hierarchy are too hard to guess exactly what setup is required: the permutations of all the tables, fields and classes that affect the outcome are too numerous to manage test by test </li></ul><ul><li>Separate database accessing tests from other tests from the very start! </li></ul>
    15. 15. Decision point <ul><li>Can you reset the whole database or not? </li></ul><ul><li>The whole database should be set/reset to a known state before each test. </li></ul><ul><li>Each developer/tester needs their own sandbox, and it should ideally be run locally </li></ul><ul><li>If you can't reset the whole database, you will have to choose maintaining state techniques or mock techniques. </li></ul>
    16. 16. Know your reset techniques <ul><li>Truncate database (unlogged) and insert test data </li></ul><ul><li>Reset proprietary database files during setup </li></ul><ul><li>Build database and test data from scratch before each test </li></ul><ul><li>Run tests in a transaction that you roll back when complete (maintain state technique) </li></ul>
    17. 17. Other ideas <ul><li>Fast, in memory databases (HSQL) </li></ul><ul><li>Ramdisks </li></ul><ul><li>File based databases (Access, dBase, SleepyCat) can just be copied if you can disconnect and close the file </li></ul><ul><li>Xml/data files on the file system </li></ul><ul><li>Anything where you can easily copy original setups can work. </li></ul>
    18. 18. Do your tests really need to hit a database? <ul><li>To many using a database in unit tests is a code smell. </li></ul><ul><ul><li>Use Mock Objects </li></ul></ul><ul><ul><li>Use Dynamic Mock Frameworks </li></ul></ul><ul><ul><li>Use alternate test based repository classes for tests </li></ul></ul><ul><li>These techniques make for much faster test speed, a major factor when the number of tests gets larger </li></ul><ul><li>These techniques can make it easier to get consistent data environments for your tests </li></ul>
    19. 19. On the other hand <ul><li>These techniques can mean a parallel hierarchy of mock/stub/fake objects for the real data access objects </li></ul><ul><li>If your tests require much data, you will be hand coding lots of data values </li></ul><ul><li>As your project changes, your test data will have to be changed in your code </li></ul><ul><li>Even if you avoid the database in unit tests, you still need integration tests with the database </li></ul>
    20. 20. Decision Point <ul><li>Test speed vs database connected tests </li></ul><ul><li>DB tests with resets are hard to get done in less than 250 ms. and longer is easy to achieve </li></ul><ul><li>Raw data is easier to manage in databases </li></ul><ul><li>Putting your test data in your test code makes it easy to find and trace and share </li></ul><ul><li>Keeping the database out of the tests allows your code to migrate along paths that make sense for code </li></ul>
    21. 21. Demonstration of reset techniques <ul><ul><li>DbUnit </li></ul></ul><ul><ul><li>Rebuild database from test data </li></ul></ul>
    22. 22. Conclusions <ul><li>DbUnit is a JUnit extension </li></ul><ul><li>The schema is maintained outside of the tool but there are places to execute a create script if you prefer </li></ul><ul><li>Also allows tests to compare raw data rather than by doing asserts against object model </li></ul><ul><li>Xml, Excel formats for data, though schema is opaque to meaning making editing challenging </li></ul>
    23. 23. Conclusions continued <ul><li>Best practices from DbUnit documentation </li></ul><ul><ul><li>“ Use one database instance per developer” </li></ul></ul><ul><ul><li>“ Good setup don't need cleanup!” </li></ul></ul><ul><ul><li>“ Use multiple small datasets” </li></ul></ul><ul><ul><li>“ Perform setup of stale data once for entire test class or test suite” </li></ul></ul>
    24. 24. Verification help <ul><li>DbUnit also has a set based Assert to compare a real data set with a canned data set. </li></ul><ul><li>Set based compares are rare </li></ul><ul><li>With an object oriented program it's often pretty easy to compare to object graphs </li></ul><ul><ul><li>Serialize “known good state” to xml </li></ul></ul><ul><ul><li>Reconstitute the graph </li></ul></ul><ul><ul><li>Write an iterator to compare the real vs expected </li></ul></ul>
    25. 25. There are alternate ways to keep test data <ul><li>Xml that makes sense to your application </li></ul><ul><li>YAML </li></ul>
    26. 26. Sample YAML from Ruby active record <ul><ul><li># Read about fixtures at </li></ul></ul><ul><ul><li>#http://ar.rubyonrails.org/classes/Fixtures.html </li></ul></ul><ul><ul><li>first_training_log: </li></ul></ul><ul><ul><li>id: 1 </li></ul></ul><ul><ul><li>notes: &quot;real easy&quot; </li></ul></ul><ul><ul><li>another_training_log: </li></ul></ul><ul><ul><li>id: 2 </li></ul></ul><ul><ul><li>intensity: 4 </li></ul></ul><ul><ul><li>notes: &quot;a bit harder today&quot; </li></ul></ul>
    27. 27. Demonstration of reset techniques <ul><ul><li>Reset Sql Server data files </li></ul></ul>
    28. 28. Reset conclusion <ul><li>Very clean way to reset a whole database </li></ul><ul><li>Can be very fast, though hardware is a big factor </li></ul><ul><li>Test data can be maintained in the DB data files and managed with normal database techniques </li></ul><ul><li>The larger the DB files get, the longer the setup time will be </li></ul><ul><li>Not all database systems have programmatic access to resets in this way </li></ul><ul><li>Not practical unless you have a local database </li></ul>
    29. 29. Demonstration of reset techniques <ul><ul><li>XtUnit </li></ul></ul><ul><ul><li>Transaction rollback cleanup </li></ul></ul>
    30. 30. XtUnit conclusions <ul><li>Very simple to do </li></ul><ul><li>Sql Server/MS windows specific </li></ul><ul><li>Your test cannot manipulate transactions themselves </li></ul><ul><li>Setup speed issues are replaced by test speed issues, it all depends on the size of the transactions </li></ul><ul><li>Can be used on a shared database across a network, making a very useful choice for some situations </li></ul><ul><li>It's possible to use the transaction technique in other environments </li></ul>
    31. 31. Demonstration of reset techniques <ul><ul><li>Reset with domain model and NHibernate </li></ul></ul>
    32. 32. NHibernate conclusions <ul><li>Setup data is encoded in your actual language using your domain model. </li></ul><ul><li>The compiler can catch many of your schema evolution issues and the test setup will catch many more </li></ul><ul><li>Depending on log issues, the test speed may be slower than some other techniques </li></ul><ul><li>Use of Hibernate/NHibernate does make it possible to use other DB systems for tests </li></ul>
    33. 33. Decision point <ul><ul><li>Mock object, or state based testing </li></ul></ul>
    34. 34. Demonstration of Mock Techniques <ul><ul><li>Domain Layer + Repository </li></ul></ul>
    35. 35. Demonstration of Mock Techniques <ul><ul><li>Record and Playback </li></ul></ul>
    36. 36. Mock Object conclusions <ul><li>Mock approaches require some degree of parallel systems </li></ul><ul><li>Dynamic mock approaches can be less code but have limitations you may not be able to live with </li></ul><ul><li>Hand coded mock approaches can do exactly what you want, but increase the work </li></ul><ul><li>Mock approaches offer a consistent and very performant way to test </li></ul><ul><li>You will be maintaining test data in code or files </li></ul>
    37. 37. Mock conclusions.... <ul><li>You may be able to avoid test data to a large degree with “behavioral” techniques </li></ul><ul><ul><li>Test that a stored procedure is called correctly </li></ul></ul><ul><ul><li>Use a Mock Object for the data access </li></ul></ul><ul><ul><li>Just “Verify()” that the data access object was called correctly and... </li></ul></ul><ul><ul><li>Assume the stored procedure is a different unit and you don't need to test the result </li></ul></ul><ul><ul><li>Testing the results is known as “State based testing” </li></ul></ul><ul><ul><li>Testing that the call was done is known as “behavioral based testing” </li></ul></ul>
    38. 38. Different decisions for different tests <ul><ul><li>Unit Test </li></ul></ul><ul><ul><li>Integration Test </li></ul></ul><ul><ul><li>Acceptance Test </li></ul></ul>
    39. 39. Unit Tests – the case for no DB <ul><li>These are repeated massively so speed really counts </li></ul><ul><li>While focusing on logic, dealing with data access can be distracting </li></ul><ul><li>A database is not part of your “Unit”, so don't introduce it in the test </li></ul><ul><li>By not using the DB, you can cross check the functionality of the unit without the assumptions of preconditions that the database might offer: nulls, default data etc. </li></ul>
    40. 40. Unit Tests – the case for using a DB <ul><li>Some logic requires lots of data: for example financial calculations and it's easier to manage lots of data with tools made for data </li></ul><ul><li>If you can afford the execution time, you are exercising your actual system much more, not a mocked or stubbed system </li></ul><ul><li>You don't have to fully architect for substitution of your data access classes. In legacy code, this may be the deal breaker </li></ul><ul><li>It's easy to use live data as examples for test cases </li></ul>
    41. 41. Unit Tests - conclusion <ul><ul><li>Unit test have natural preference to avoid the use of databases. However, you can make it work up to a point. On new code, I would suggest learning to live without, but on code that doesn't easily support the architecture, learn the tools needed and live with the database. </li></ul></ul>
    42. 42. Integration Tests – the case for no DB <ul><ul><li>There really isn't a case for no DB, these are integration tests where parts of the system come together. </li></ul></ul>
    43. 43. Integration Tests – conclusion <ul><ul><li>Integration tests are most often run as part of a continuous or daily build process. The speed is less a factor and exercising real code is paramount. </li></ul></ul>
    44. 44. Acceptance tests <ul><ul><li>There hasn't been much said about databases with acceptance tests. I have many stories to tell about QA testers that have to go through great agony to rerun tests, but generally systems are rebuilt daily at most. This is an interesting area for further research in the quest of better testing productivity. </li></ul></ul>
    45. 45. Conclusions <ul><li>Can you work with a local database? </li></ul><ul><li>Can you reset a local database with any of the techniques presented here? </li></ul><ul><li>Would your architecture or programming culture accept mock techniques for testing? </li></ul><ul><li>Separate database connected tests from the others </li></ul><ul><li>What is a reasonable time for your test run to take? </li></ul>
    46. 46. Schema evolution <ul><li>Release day – capture current schema from live </li></ul><ul><li>Current live + alter scripts to test databases </li></ul><ul><li>Alter scripts as part of daily build </li></ul><ul><li>Depending on the number of changes, you may need to run alter scripts against test databases </li></ul><ul><li>Alternatively, automate the daily test schema </li></ul><ul><li>After QA cycle, run alter scripts during release to live </li></ul>
    47. 47. Questions?

    ×