Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Test-driven development in Android by Illia Kon...

Test-driven development in Android by Illia Kondratov

Introduction for people who never tried TDD or unit testing before, or struggle with some part of it. We’ll cover benefits, discuss best practices and see what people mean when they say “it’s better to have unit-tests here”.

https://gdgmontreal.com/2019/10/17/october-meetup-2019/

GDG Montreal

October 23, 2019
Tweet

More Decks by GDG Montreal

Other Decks in Programming

Transcript

  1. What is a unit test? @Test public void testSqrtWith25 ()

    { //PREPARE SomeObjectToTest object = new SomeObjectToTest() ; //PERFORM int result = object.sqrt( 25); //CHECK assertEquals(5, result); }
  2. Unit tests benefits 1) The only documentation that is always

    up to date 2) Making refactoring really possible 3) Adding new features without risks 4) Continuous testing
  3. F.I.R.S.T 1) Fast 2) Independent 3) Repeatable 4) Self-Validating 5)

    Timely Three 1’s 1) ONE logical branch 2) ONE concept to test 3) ONE way to structure Your testing is a joke © James Thomas
  4. Smells of bad tests in the morning 1) If 2)

    assertTrue(x == y); 3) Evergreen tests 4) Test avalanche twice a week 5) Discussing private matters with your test 6) Reflection 7) Testing toString() 8) It’s hard to name the test
  5. If your code wasn’t designed to be testable - it

    is not 1) Non-injected dependencies 2) Android framework dependencies 3) Static methods and variables
  6. Three Rules of TDD 1) If there is no test

    - there is no code 2) You write as much of the test as required for it to fail 3) You write as much of the code as required for the test to pass
  7. Step 1: If there is no test - there is

    no code @Test public void testSqrtWith25 () { //PREPARE SomeObjectToTest object = new SomeObjectToTest() ; //PERFORM int result = object.sqrt( 25); //CHECK } public class SomeObjectToTest {}
  8. Step 2: make your test pass... @Test public void testSqrtWith25

    () { //PREPARE SomeObjectToTest object = new SomeObjectToTest() ; //PERFORM int result = object.sqrt( 25); //CHECK } public class SomeObjectToTest { public int sqrt(int value) { return 0; } }
  9. Step 3: ...and then make it fail again @Test public

    void testSqrtWith25 () { //PREPARE SomeObjectToTest object = new SomeObjectToTest() ; //PERFORM int result = object.sqrt( 25); //CHECK assertEquals(5, result); //assertTrue(5 == result); } public class SomeObjectToTest { public int sqrt(int value) { return 0; } }
  10. What TDD is not 1) It’s not a religion -

    you change the rules the way it fits you 2) It’s not a silver bullet - it’s not making your code perfect instantly 3) It’s not a universal solution - it might be not required