Best practices for writing good automated tests

6,334 views

Published on

Best practices for writing good automated tests

  1. 1. Best practices for writing automated tests Felipe Limafelipe@gogobot.com @felipecsl
  2. 2. • Assumption 1: You are already convinced that automated tests are good
  3. 3. • Assumption II: You agree that best way to accomplish that is writing tests before you code.
  4. 4. What is considered to be a good test?
  5. 5. Structure - AAA:• Arrange• Act• Assert
  6. 6. What makes a good test?
  7. 7. • Assumes a clean environment (empty database, redis, solr, etc.)• Cleans up after itself• Runs quickly• Readable, simple to understand• Tests only one thing at a time
  8. 8. • Isolates the class you are testing• Stubs external dependencies (eg.: vcr)• Thorough: covers happy and edge cases• Repeatable: always provides same results• Doesn’t make unnecessary assertions• Clearly and consistently named
  9. 9. SOLID• Single Responsibility Principle• Open/closed principle• Liskov substitution principle• Interface segregation principle• Dependancy Inversion principle
  10. 10. Why write tests before the code?
  11. 11. • SOLID code is HIGHLY testable• TDD forces you to think about your design• Bad code is hard to test• It is a design process, not a testing process
  12. 12. “TDD is a robust way of designingsoftware components (“units”)interactively so that their behaviour isspecified through unit tests.” http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/
  13. 13. http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/
  14. 14. TDD Mantra:Red => Green => Refactorhttp://www.agileapps.co.uk/methodology/continuous.html
  15. 15. Mocks and Stubs:• Mocks set up expectations on messages that are passed between objects• Stubs provide canned answers to calls made during the test• Only mocks specify expected behavior and make assertions• Also know as test doubles (eg.: in RSpec) Reference: http://martinfowler.com/articles/mocksArentStubs.html
  16. 16. Stub example:controller.stub(:current_user).and_return(fake_user)Mock example:user.should_receive(:postcards).and_return([p1, p2, p3])postcards = controller.postcards(user.id)postcards.should =~ [p1, p2, p3]

×