Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Developer Test - Things to Know

587 views

Published on

Presenation slides given at Kaunas JUG 2014-10-15

Published in: Engineering
  • Be the first to comment

  • Be the first to like this

Developer Test - Things to Know

  1. 1. Developer Tests Things to Know Vaidas Pilkauskas 2014 Kaunas JUG vaidas.pilkauskas@gmail.com
  2. 2. “We couldn’t understand why people without technical knowledge had to tell programmers “what” to do and, furthermore, they had to supervise “how” programmers did it.” Cristian Rennella http://qz.com/260846/why-our-startup-has-no-bosses-no-office-and-a-four-day-work-week/
  3. 3. What I’m going to talk about ● Things we argue about during code reviews ● Things that took me time to understand and prove that they are actually good way to go ● Small things we have no time to discuss during big talks
  4. 4. “Legacy Code is code without Tests” Michael Feathers Working Effectively with Legacy Code
  5. 5. So what is test? It is system’s exercise under predefined conditions and then verification of an expected outcome.
  6. 6. Thing #1 Test phases
  7. 7. Test phases 1. Set up 2. Exercise 3. Verify 4. Tear down
  8. 8. Test phases @Test public void serverShouldExecuteJobSuccessfully() { Server server = new Server(); // set up Job job = new Job(); // set up Status status = server.execute(job); // exercise assertEquals(SUCCESS, status); // verify server.shutdown(); // tear down }
  9. 9. @Before public void before() { server = new Server(); } @Test public void serverShouldExecuteJobSuccessfully() { Job job = new Job(); // set up Status status = server.execute(job); // exercise assertEquals(SUCCESS, status); // verify server.shutdown(); // tear down }
  10. 10. @Before public void before() { server = new Server(); Job job = new Job(); } @Test public void serverShouldExecuteJobSuccessfully() { Status status = server.execute(job); // exercise assertEquals(SUCCESS, status); // verify server.shutdown(); // tear down }
  11. 11. @Test public void serverShouldQueueJobWithFutureDate() { // * set up which is actual for the current method // * use scope specific name Job futureJob = new Job(futureDate()); // set up Status status = server.execute(futureJob); // exercise assertEquals(SUCCESS, status); // verify server.shutdown(); // tear down }
  12. 12. @Before public void before() { server = new Server(); Job job = new Job(); } @Test public void serverShouldExecuteJobSuccessfully() { Status status = server.execute(job); // exercise assertEquals(SUCCESS, status); // verify } @After public void after() { server.shutdown(); // tear down }
  13. 13. @Before .. @Test public void serverShouldExecuteJobSuccessfully() { // * no need to name intermediate var, but // * may hide return meaning of server.execute() // execute & verify assertEquals(SUCCESS, server.execute(job)); } @After ..
  14. 14. Set up ● DRY principle
  15. 15. Set up ● DRY principle ● Readability
  16. 16. Set up ● DRY principle ● Readability ● Consistency
  17. 17. Set up ● DRY principle ● Readability ● Consistency ● Complexity
  18. 18. Refactoring Refactoring is about improving the design of existing code. It is the process of changing a software system in such a way that it does not alter the external behavior of the code, yet improves its internal structure. Martin Fowler Refactoring: Improving the Design of Existing Code
  19. 19. Thing #2 What do we test?
  20. 20. Test behaviour not methods ● Think of a contract
  21. 21. Test behaviour not methods ● Think of a contract ● And responsibilities
  22. 22. Test behaviour not methods ● Think of a contract ● And responsibilities ● Specify requirements as tests
  23. 23. Test behaviour not methods ● Think of a contract ● And responsibilities ● Specify requirements as tests ● Happens naturally when done in test-first approach
  24. 24. Thing #3 Matchers
  25. 25. Matchers ● Enhanced readability ● Assertions on the right level of abstraction ● Encapsulate testing logic ● Reusable ● Detailed match error messages (do not leave them out in your custom matchers!)
  26. 26. Matcher libraries ● Hamcrest - standard matcher lib for JUnit ● AssertJ - fluent assertions (IDE friendly) ● Bring common matchers for you to use ● Write your own custom matchers
  27. 27. Hamcrest assertThat(theBiscuit, equalTo(myBiscuit)); assertThat(theBiscuit, is(equalTo(myBiscuit))); assertThat(theBiscuit, is(myBiscuit));
  28. 28. AssertJ assertThat(frodo.getName()).isEqualTo("Frodo"); assertThat(frodo).isNotEqualTo(sauron) .isIn(fellowshipOfTheRing); assertThat(sauron).isNotIn(fellowshipOfTheRing);
  29. 29. Thing #4 Custom matchers
  30. 30. Custom matchers Are matchers we develop specifically for our projects
  31. 31. Custom matchers ● Help communicate test intention ● Abstract assertion logic in case standard matchers are not enough ● Are reusable and save time in large projects ● You may have custom message to be more specific about test failure
  32. 32. Custom matchers @Test public void testBookIsbn() { Book book = new Book(1l, "5555", "A book"); assertThat(book, hasIsbn("1234")); }
  33. 33. Thing #5 Failing test
  34. 34. fail() In some cases like testing exceptions you may want to force test to fail if some expected situation does not happen
  35. 35. fail() try{ // do stuff... fail("Exception not thrown"); }catch(Exception e){ assertTrue(e.hasSomeFlag()); }
  36. 36. fail() ● Fundamentally not bad, but better use matchers for expected failure ● Matchers help to clarify test intention ● Don’t forget - expected behaviour is an opposite of a failing test
  37. 37. Thing #6 Anti-pattern: The Ugly Mirror
  38. 38. Anti-pattern: The Ugly Mirror @Test public void personToStringShouldIncludeNameAndSurname() { Person person = new Person("Vilkas", "Pilkas"); String expected = "Person[" + person.getName() + " " + person.getSurname() + "]" assertEquals(expected, person.toString()); }
  39. 39. Anti-pattern: The Ugly Mirror @Test public void personToStringShouldIncludeNameAndSurname() { Person person = new Person("Vilkas", "Pilkas"); String expected = "Person[" + person.getName() + " " + person.getSurname() + "]" assertEquals(expected, person.toString()); }
  40. 40. Anti-pattern: The Ugly Mirror @Test public void personToStringShouldIncludeNameAndSurname() { Person person = new Person("Vilkas", "Pilkas"); assertEquals("Person[Vilkas Pilkas]", person.toString()); }
  41. 41. Thing #7 How to turn off the test?
  42. 42. Why would you want to turn off the test? ● Well, because it fails… :)
  43. 43. Ignoring tests ● Always use ignore/pending API from your test library (JUnit @Ignore)
  44. 44. Ignoring tests ● Always use ignore/pending API from your test library (JUnit @Ignore) ● Do not comment out or false assert your test
  45. 45. Ignoring tests ● Always use ignore/pending API from your test library (JUnit @Ignore) ● Do not comment out or false assert your test ● If you do not need a test - delete it
  46. 46. Thing #8 What to do with exceptions?
  47. 47. Exceptions ● If you can, use matchers instead of ○ @Test(expected=?)
  48. 48. JUnit expected exception @Test(expected=IndexOutOfBoundsException.class) public void shouldThrowIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } //matcher in Specs2 (Scala) server.process(None) must throwA[NothingToProccess]
  49. 49. Exceptions ● If you can, use matchers instead of ○ @Test(expected=?) ○ try-catch approach
  50. 50. try and catch public void shouldThrowIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); try { Object o = emptyList.get(0); fail("Should throw IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException e)){ //consider asserting message! } }
  51. 51. Exceptions ● If you can, use matchers instead of ○ @Test(expected=?) ○ try-catch approach ● catch-exception lib
  52. 52. catch-exception lib List myList = new ArrayList(); catchException(myList).get(1); assertThat(caughtException(), allOf( is(IndexOutOfBoundsException.class), hasMessage("Index: 1, Size: 0"), hasNoCause() ) );
  53. 53. Exceptions ● If you can, use matchers instead of ○ @Test(expected=?) ○ try-catch approach ● catch-exception lib ● What about ExpectedException Rule? ○ My personal opinion - not that intuitive ○ breaks arrange/act/assert flow
  54. 54. ExpectedException rule @Rule public ExpectedException exception = ExpectedException.none(); @Test public void testExpectedException() { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString('Invalid age')); new Person('Vilkas', -1); } //Person constructor public Person(String name, int age) { if (age <= 0) throw new IllegalArgumentException('Invalid age:' + age); // ... }
  55. 55. Thing #9 How to test asynchronous code?
  56. 56. Asynchronous code ● Do not Thread.sleep - makes test slow
  57. 57. Asynchronous code ● Do not Thread.sleep - makes test slow ● Use Awaitility, or similar DSL for synchronizing asynchronous operations
  58. 58. Awaitility (Java 8 example) @Test public void shouldPersistNewUser() { publish(new CreateUserCommand("Vilkas Pilkas")); await().until(userRepo::size, is(1)); //how long to await? (Default is 10 seconds) await().until(userRepo::isNotEmpty); }
  59. 59. Asynchronous code ● Do not Thread.sleep - makes test slow ● Use Awaitility, or similar DSL for synchronizing asynchronous operations ● Use reasonable await time to avoid flaky tests
  60. 60. Thing #10 Testing with time
  61. 61. Problem public class MyService { ... public void process(LocalDate date) { if (date.isBefore(LocalDate.now()) { ... } } }
  62. 62. Testing with Time ● Design your system where time is a collaborator ● Inject test specific time provider in your test ○ constant time ○ slow time ○ boundary cases time
  63. 63. Control time with Clock public class MyService { private Clock clock; // dependency inject ... public void process(LocalDate date) { if (date.isBefore(LocalDate.now(clock)) { ... } } }
  64. 64. Thing #11 Collections
  65. 65. Collections - multiple properties to assert ● Is null? ● Size ● Order ● Content
  66. 66. Collections ● Most of the time you want to assert on collection content
  67. 67. Collections ● Most of the time you want to assert on collection content ● Prefer exact content matching
  68. 68. Collections ● Most of the time you want to assert on collection content ● Prefer exact content matching ● Avoid incomplete assertions
  69. 69. Collections ● Most of the time you want to assert on collection content ● Prefer exact content matching ● Avoid incomplete assertions ● Do not sort just because it is easier to assert!
  70. 70. Collections ● Most of the time you want to assert on collection content ● Prefer exact content matching ● Avoid incomplete assertions ● Do not sort just because it is easier to assert! ● Multiple assertions are worse than single content assertion
  71. 71. Collections ● Most of the time you want to assert on collection content ● Prefer exact content matching ● Avoid incomplete assertions ● Do not sort just because it is easier to assert! ● Multiple assertions are worse than single content assertion ● Unless you want to say something important in your test!
  72. 72. Collections ● Most of the time you want to assert on collection content ● Prefer exact content matching ● Avoid incomplete assertions ● Do not sort just because it is easier to assert! ● Multiple assertions are worse than single content assertion ● Unless you want to say something important in your test! ● Use matchers!
  73. 73. Thing #12 Access modifiers
  74. 74. Access modifiers ● Rule is simple - never access anything that is not public in your tests
  75. 75. Access modifiers ● Rule is simple - never access anything that is not public in your tests ● Private things are implementation details which are not part of the public contract
  76. 76. Access modifiers ● Rule is simple - never access anything that is not public in your tests ● Private things are implementation details which are not part of the public contract ● Same applies for protected/package modifiers. They must be there for production code, but not available to your tests
  77. 77. Thing #13 Random values
  78. 78. Random values in tests ● Most of the time you do not want it
  79. 79. Random values in tests ● Most of the time you do not want it ● Unless you depend on randomness a lot (eg. password generation*) *Thanks to Aleksandar Tomovski for a good example
  80. 80. Random values in tests ● Most of the time you do not want it ● Unless you depend on randomness a lot ● Use property based testing (which is also hard)
  81. 81. Random values in tests ● Most of the time you do not want it ● Unless you depend on randomness a lot ● Use property based testing (which is also hard) ● Do not make dummy values random
  82. 82. What if we still need random cases?
  83. 83. Generate Multiple Test Cases ● Quality over quantity
  84. 84. Generate Multiple Test Cases ● Quality over quantity ● Think of boundary cases, that you may want to detect with random test
  85. 85. Generate Multiple Test Cases ● Quality over quantity ● Think of boundary cases, that you may want to detect with random test ● Use parameterized tests
  86. 86. Generate Multiple Test Cases ● Quality over quantity ● Think of boundary cases, that you may want to detect with random test ● Use parameterized tests ● Random is hard to repeat
  87. 87. Generate Multiple Test Cases ● Quality over quantity ● Think of boundary cases, that you may want to detect with random test ● Use parameterized tests ● Random is hard to repeat ● Flickering tests
  88. 88. Thing #14 How many assertions per test?
  89. 89. How many assertions per test? ● Unit test - one assertion per test. Must be clear and readable ● Proper unit tests should fail for exactly one reason ● End to end - best case one assertions per test, but more allowed ● Consider custom matchers
  90. 90. Thing #15 Test Doubles
  91. 91. Test Doubles The name comes from the notion of a Stunt Double in movies
  92. 92. Why do we need test doubles? ● To test in an isolated environment by replacing real collaborators with doubles ● To have fast tests ● To test interactions ● To change collaborators behaviour in test
  93. 93. Types of Test Doubles ● Dummy ● Fake ● Stub ● Spy ● Mock
  94. 94. Dummy Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists
  95. 95. Fake Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example)
  96. 96. Stub Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'
  97. 97. Spy Stubs that verify behavior
  98. 98. Mock Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive
  99. 99. So what’s the difference between Spy and Mock?
  100. 100. Thing #16 Naming
  101. 101. Where to keep your tests ● Recommendation: keep them in separate package from production code
  102. 102. Class Naming ● End test classes with Test suffix (or one required by your test framework) ● For long test classes: ○ split by feature ○ by input type
  103. 103. Method Naming ● Everybody should follow the same pattern ● testGeneratePassword vs shouldGenerateValidPassword
  104. 104. Naming Test Doubles ● Intention revealing stubEngine, spyServer, dummyUser, mockService
  105. 105. Thing #17 Comments
  106. 106. Comments in Test code ● Fundamentally good option to explain complicated parts, but: ● better use good method naming ● custom matcher ● do less, so that intention is clear ● comments are not so bad in isolated well named set up method (not the first thing to be seen in test method)
  107. 107. Thanks! Q & A

×