Intro to unit testing     Steven Casey     twitter.com/stevencasey
An intro to a test of a unitObligatory wikipedia quote: “unit testing is amethod by which individual units of source code,...
What to testeverything? nothing? what I feel like?Its a tough decision to decide where to draw theline between the obvious...
• Lots of tests, will cost more to maintain over  time and always have the potential to create  almost as many problems as...
Tightrope?• Absolutely. One that requires discipline. Tests  should be first-class code citizens.• Otherwise they can beco...
So, what to test?Use the force? Guess?Or, you can rely on a mix of complexity analysis (get yercyclomatic complexity analy...
What not to test?What doesn’t add value?- Code that never changes (or least likely to…)  AND isn’t broken (yet)- Code that...
What not to test• Globals, statics, persistent data (DB, IO),  distributed data (memcache)• You will quickly find yourself...
How to structure a test?Arrange Act Assert: a sample…[TestMethod]public void RegisterWithValidInputs_SendsEmailForVerifica...
RR Record-Replay• Record-Replay: for me, mind bending. I much  prefer AAA and just about every OSS project I  see does too...
Test structure, syntax• Follow a naming convention for tests.• A Suggestion is that you first name the method  you are tes...
Test SetupAvoid IOC. Testing your code is easier withoutregistration logic.Use a mocking framework only for non-trivialdep...
Some tips on writing tests…• Change code first, then tests. If u change both  at once, well, how do u know which is broken...
more tips…• Don’t create methods/props in production  code only for use by tests (can you smell the  bad design?)• 1 test ...
Mocks, fakes, stubs, huh?• Stub: replaces implementation with code that returns a  specific result. No asserts on stub.• M...
A test of sorts…So finally, all your tests pass, w00t! But, someonefinds a bug. What should your next steps be?If you said...
FinInitially written & presented 2010 @ communityengine. later adapted& posted for posterity here to have a nice reference...
Upcoming SlideShare
Loading in …5
×

An Introduction to unit testing

2,681 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,681
On SlideShare
0
From Embeds
0
Number of Embeds
12
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

An Introduction to unit testing

  1. 1. Intro to unit testing Steven Casey twitter.com/stevencasey
  2. 2. An intro to a test of a unitObligatory wikipedia quote: “unit testing is amethod by which individual units of source code,sets of one or more computer program modulestogether with associated control data, usageprocedures, and operating procedures, aretested to determine if they are fit for use”(emphasis mine)http://en.wikipedia.org/wiki/Unit_testing
  3. 3. What to testeverything? nothing? what I feel like?Its a tough decision to decide where to draw theline between the obvious safety net of unit testsand the cost of writing & maintaining those unittests.
  4. 4. • Lots of tests, will cost more to maintain over time and always have the potential to create almost as many problems as they solve.• BUT…• A lack of tests, doesn’t give you confidence to work with the glorious safety net that really good test coverage provides.• and, more importantly, quality assurance & rapid feedback
  5. 5. Tightrope?• Absolutely. One that requires discipline. Tests should be first-class code citizens.• Otherwise they can become useless, ignored, a dead pool of code that no-one wants to maintain. Then you have a new kind of legacy codebase… sad face
  6. 6. So, what to test?Use the force? Guess?Or, you can rely on a mix of complexity analysis (get yercyclomatic complexity analysis ON), branches & iterations arecandidates hereMaybe, also considering edge-cases/boundary conditions forcore business functions (xunit/mbunit for iterative testingrocks!)Or, if you have a legacy codebase. What are the hot classesalways changing? Wouldn’t it be nice if you could wrap thosein tests and optimize that code with confidence!
  7. 7. What not to test?What doesn’t add value?- Code that never changes (or least likely to…) AND isn’t broken (yet)- Code that cannot be mocked/faked. EG calling an API.- Non-public code! Only test the public interface of your class under test, not the internal implementation.
  8. 8. What not to test• Globals, statics, persistent data (DB, IO), distributed data (memcache)• You will quickly find yourself thinking, how can I test this and (hopefully) deciding to avoid globals & statics as much as possible.• Does your test connect to a shared db? Ok, stop! You cannot guarantee a repeatable isolated test there can you? Stay tuned for details on mocks/fakes/stubs!
  9. 9. How to structure a test?Arrange Act Assert: a sample…[TestMethod]public void RegisterWithValidInputs_SendsEmailForVerification(){ // Arrange var register = _sut.RegisterNotifications; // Act var result = _sut.Index(new RegisterUserViewModel(){ Password = "password", Email = "john@smith.com", FirstName = "john", LastName = "smith“ }) as ViewResult; // Assert register.ReceivedWithAnyArgs().SendUserActivationActionEmail(null);}
  10. 10. RR Record-Replay• Record-Replay: for me, mind bending. I much prefer AAA and just about every OSS project I see does too. So, I will not cover it here.• For more, read: http://ayende.com/wiki/Rhino+Mocks+Record -playback+Syntax.ashx
  11. 11. Test structure, syntax• Follow a naming convention for tests.• A Suggestion is that you first name the method you are testing, the inputs, and the expected result. Be descriptive over shorthand, these descriptions will help identify quickly what test is failing when you have several hundred (or thousand) tests.• Alternative conventions exist: – GivenWhenThen syntax (my favourite approach for BDD-style tests)
  12. 12. Test SetupAvoid IOC. Testing your code is easier withoutregistration logic.Use a mocking framework only for non-trivialdependencies. I recommend Nsubstitute!The testing framework usually has 2 types. One forclass level and one method level which runsbefore/after every test.Use the method setup and teardown methods forcreating and destroying the system(class) undertest, to ensure a clean SUT for each test & keep therepetitive code out of your tests.
  13. 13. Some tips on writing tests…• Change code first, then tests. If u change both at once, well, how do u know which is broken!• Test’s should be independent of one another• Test one thing (behaviour) per test. (yes, its ok to have multiple asserts, as long as they all test the same behaviour)• No conditional logic, no loops, no exception catching (unless its an expected exception)• No test logic in production code
  14. 14. more tips…• Don’t create methods/props in production code only for use by tests (can you smell the bad design?)• 1 test class = 1 class under test (don’t mix the classes you are testing, it gets confusing quickly!)
  15. 15. Mocks, fakes, stubs, huh?• Stub: replaces implementation with code that returns a specific result. No asserts on stub.• Mock: all about asserting that something has been called, perhaps with particular params• Fake: anything that is not a ‘real’ implementation. You may create a fake to validate behaviours of SUT or to return specific results.• http://www.martinfowler.com/articles/mocksArentStubs.ht ml
  16. 16. A test of sorts…So finally, all your tests pass, w00t! But, someonefinds a bug. What should your next steps be?If you said/thought…write a test to repro the bug and then fix the test.Well sir (or madam) , I think you got it! 
  17. 17. FinInitially written & presented 2010 @ communityengine. later adapted& posted for posterity here to have a nice reference for hopefullyencouraging others to improve their approach to testing.Steven Casey. twitter.com/stevencasey. feedback encouraged! References:• http://blog.stevensanderson.com/2009/08/24/writing-great-unit- tests-best-and-worst-practises/• http://www.slideshare.net/nickokiss/unit-testing-best-practices• Art of Unit Testing by Roy Osherove (read it!)

×