SlideShare a Scribd company logo
1 of 23
15 tips
to improve your
unit tests
Droidcon 2016 Barcamp
@PreusslerBerlin
What makes a clean test?
Three things.
Readability,
readability,
and readability
Uncle Bob, Clean Code
#1 Don‘t start your test methods with „test“
• That‘s Junit3 way
• Junit4 was released 10 years ago!
• Prevents good method names
@Test
public void should_stop_sync_if_error()
#2 Have consistent naming
• Have one name for the instance under test
Don‘t let the reader guess which class is tested
public class MessageTest {
Parcel parcel = mock(Parcel.class);
Message tested = new Message("subject", “text“);
@Test
public void should_write_to_parcel() {
tested.writeToParcel(parcel, 0);
...
#3 Don‘t use pure junit asserts!
• Nobody remembers actual and expected order
• Hamcrest matchers:
• FEST assertions:
assertThat(yoda).isInstanceOf(Jedi.class)
.isEqualTo(foundJedi)
.isNotEqualTo(foundSith);
assertThat("test", anyOf(is("testing"), containsString("est")));
#4 The test method is the most import part
• Move as much code out of test as possible to setup or init-block
• 90% of readers won‘t need that
@Test
public void should_not_be_empty() {
when(login.isLoggedIn()).thenReturn(true);
when(options.showDashboardValues()).thenReturn(true);
assertFalse(tested.isEmptyDashboardShown());
}
#4 The test method is the most import part
• Move as much code out of test as possible to setup or init-block
• 90% of readers won‘t need that
@Before
public void setup() {
login = mock(Login.class);
when(login.isLoggedIn()).thenReturn(true);
options = mock(DisplayOptions.class);
displayUtil = mock(DisplayUtil.class);
when(options.showDashboardValues()).thenReturn(true);
tested = new ContentFragmentBuilderPhone(login, options, displayUtil);
}
#4 The test method is the most import part
• Move as much code out of test as possible to setup or init-block
• Don‘t do both:
Place place = new Place("1", "one", Location.NONE);
Merchant merchant1 = new Merchant("1", "one", MerchantAccessLevel.FULL_ACCESS);
Merchant merchant2 = new Merchant("2", "two", MerchantAccessLevel.FULL_ACCESS);
PlaceListTabletFragment tested = spy(new PlaceListTabletFragment());
@Before
public void setup() {
tested.places = new Places(Arrays.asList(place));
tested.merchant = merchant1;
tested.interactor = mock(LoginInteractor.class);
tested.loggedInUser =
new LoggedInUser(NO_USER,NO_TOKEN, Arrays.asList(merchant1, merchant2), NO_PLACE);
}
#5 No javadoc to explain the test steps
@Test
public void testGetParentScope_shouldReturnRootScope_whenAskedForSingleton() {
//GIVEN
Scope parentScope = Toothpick.openScope("root");
Scope childScope = Toothpick.openScopes("root", "child");
//WHEN
Scope scope = childScope.getParentScope(Singleton.class);
//THEN
assertThat(scope, is(parentScope));
}
#1
#4
Scope parentScope = Toothpick.openScope("root");
Scope childScope = Toothpick.openScopes("root", "child");
@Test
public void should_return_root_scope () {
Scope scope = childScope.getParentScope(Singleton.class);
assertThat(scope, is(parentScope));
}
#5 No javadoc to explain the test steps
#6 Reduce the noise: readability first
• No finals, nor private fields
• No final on methods or variables
• Test instances don‘t see each other
it is safe to violate encapsulation in tests!
private final Place place = new Place("1", "one“);
private final Merchant merchant = new Merchant("1", "one“);
#7 Always implement equals!
Keeps test short and readable
assertThat(tested.getUser())
.isEqualTo(new User(“danny”));
#8 Add matcher for your models
• anyDeal() instead of any(Deal.class)
• mockDeal() instead of mock(Deal.class)
• For android check out github.com/dpreussler/mockitoid
#9 Use the Null-Object pattern
• Prefer Optionals over null
• Prefer Null-Object over optionals
• Prefer Null-Object over mocks as mocks dont respect nonnull contract
• Often in tests you just need the right type, not a specific new instance
-> reduce test garbage
tested.redeem(Deal.NO_DEAL, mock(EventBus.class));
#10 Have default implemenations
@Singleton
public class UiFlavors {
public static final UiFlavors TABLET = new UiFlavors(true);
public static final UiFlavors PHONE = new UiFlavors(false);
private final boolean isTablet;
@Inject
public UiFlavors(Resources resources) {
this(detectTablet(resources));
}
...
Filled on runtime
For tests and equal checks
#10 Have default implemenations
@Singleton
public class UiFlavors {
public static final UiFlavors TABLET = new UiFlavors(true);
public static final UiFlavors PHONE = new UiFlavors(false);
private final boolean isTablet;
@Inject
public UiFlavors(Resources resources) {
this(detectTablet(resources));
}
...
@Test
public void should_add_custom_dimension_for_phone() {
TrackingImpl tested = new TrackingImpl(UiFlavors.PHONE, mockContext());
tested.setCustomDimensions(eventBuilder);
verify(eventBuilder).setCustomDimension(1, "phone");
}
#11 Write readable Reflection code
SuperReflect.on(
Build.VERSION.class)
.set("SDK_INT", 14);
Fluent interface, good for setting values (incl. finals) in API/ 3rd party/ code
github.com/dpreussler/SuperReflect
SuperReflect.on(tested)
.get(“privateField“);
#11 Write readable Reflection code
@BoundBox( boundClass = A.class )
private BoundBoxOfA tested;
@Test
public void test() {
tested = new BoundBoxOfA( new A("bb") );
tested.boundbox_privateField()
}
Generate getters for private fields (compiletime-safe)
github.com/stephanenicolas/boundbox
#12 Don‘t be too strict on „units“
Real world API JSON parsing and conversion to models
is a large unit but very useful test
@Test
public void can_read_from_json() throws IOException {
String values = inputStreamToString(JsonDealsTest.class.getResourceAsStream(“/deals.json"));
JsonDeals out = new Gson().fromJson(values, JsonDeals.class);
List<Deal> deals= out.asDealList();
assertThat (deals.get(0).getTitle()).isEqualTo(“First TestTitle“);
}
#13 If you can not test, then it‘s not good code
Do you know the rule about encapsulation and tests?
Uh, no. What rule is that?
Tests trump Encapsulation.
What does that mean?
That means that tests win.
No test can be denied access to a variable
simply to maintain encapsulation.
Uncle Bob (https://blog.8thlight.com/uncle-bob/2015/06/30/the-little-singleton.html)
#14 Inversion of Control
If you create objects (especially views) in a constructor,
overload another constructor for testing
public OptionsViewHolder(View itemView) {
this(itemView, new DealAnalyticsView(itemView, formatter));
}
@VisibleForTesting
OptionsViewHolder(View itemView, DealAnalyticsView analyticsView){
...
#15 Make it fail!
The pupil went to the master programmer and said:
“All my tests pass all the time. Don’t I deserve a raise?”
The master slapped the pupil and replied:
“If all your tests pass, all the time, you need to write better tests.”
Good tests fail
The Way of Testivus, Alberto Savoia
http://www.agitar.com/downloads/TheWayOfTestivus.pdf
Unit testing is no
rocket science!
@PreusslerBerlin
Thank you!

More Related Content

What's hot

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYCMike Dirolf
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsClare Macrae
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Anton Arhipov
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingAnton Arhipov
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitMichelangelo van Dam
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentationnicobn
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistAnton Arhipov
 
Android Unit Testing With Robolectric
Android Unit Testing With RobolectricAndroid Unit Testing With Robolectric
Android Unit Testing With RobolectricDanny Preussler
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for ProgrammersDavid Rodenas
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistAnton Arhipov
 

What's hot (20)

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
groovy & grails - lecture 7
groovy & grails - lecture 7groovy & grails - lecture 7
groovy & grails - lecture 7
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDD
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
 
Android Unit Testing With Robolectric
Android Unit Testing With RobolectricAndroid Unit Testing With Robolectric
Android Unit Testing With Robolectric
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
 
JS and patterns
JS and patternsJS and patterns
JS and patterns
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 

Viewers also liked

Asian crisis final
Asian crisis  finalAsian crisis  final
Asian crisis finalAli Ussama
 
A Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa Chemicals
A Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa ChemicalsA Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa Chemicals
A Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa ChemicalsSadman Ahmed
 
106M 1997 Asian Financial Crisis
106M 1997 Asian Financial Crisis106M 1997 Asian Financial Crisis
106M 1997 Asian Financial CrisisGary Vartanian
 
South east asian financial crises 1997
South east asian financial  crises 1997South east asian financial  crises 1997
South east asian financial crises 1997Praveen Ravuri
 
Asian Financial Crisis
Asian Financial CrisisAsian Financial Crisis
Asian Financial CrisisFNian
 
Module 6 6 globalization foreign trade, wto
Module 6 6 globalization foreign trade, wtoModule 6 6 globalization foreign trade, wto
Module 6 6 globalization foreign trade, wtoIndependent
 
Asian financial crisis 1997
Asian financial crisis   1997Asian financial crisis   1997
Asian financial crisis 1997Sandeep Bhattad
 

Viewers also liked (13)

Toothpick & Dependency Injection
Toothpick & Dependency InjectionToothpick & Dependency Injection
Toothpick & Dependency Injection
 
Lampiran unit root test
Lampiran unit root testLampiran unit root test
Lampiran unit root test
 
Asian crisis final
Asian crisis  finalAsian crisis  final
Asian crisis final
 
A Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa Chemicals
A Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa ChemicalsA Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa Chemicals
A Case Study Analysis on the Asian Financial Crisis of 1997 and Zapa Chemicals
 
106M 1997 Asian Financial Crisis
106M 1997 Asian Financial Crisis106M 1997 Asian Financial Crisis
106M 1997 Asian Financial Crisis
 
South east asian financial crises 1997
South east asian financial  crises 1997South east asian financial  crises 1997
South east asian financial crises 1997
 
Asian crisis 1997
Asian crisis 1997Asian crisis 1997
Asian crisis 1997
 
Asian Financial Crisis
Asian Financial CrisisAsian Financial Crisis
Asian Financial Crisis
 
Module 6 6 globalization foreign trade, wto
Module 6 6 globalization foreign trade, wtoModule 6 6 globalization foreign trade, wto
Module 6 6 globalization foreign trade, wto
 
Asian financial crisis 1997
Asian financial crisis 1997Asian financial crisis 1997
Asian financial crisis 1997
 
Unit Root Test
Unit Root TestUnit Root Test
Unit Root Test
 
Unit Root Test
Unit Root Test Unit Root Test
Unit Root Test
 
Asian financial crisis 1997
Asian financial crisis   1997Asian financial crisis   1997
Asian financial crisis 1997
 

Similar to 15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)

Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesNarendra Pathai
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testMasanori Kato
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113SOAT
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
 
Pitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz BankowskiPitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz BankowskiAgileee
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionSchalk Cronjé
 
Introduction to Voice I/O on Android
Introduction to Voice I/O on AndroidIntroduction to Voice I/O on Android
Introduction to Voice I/O on AndroidJorge Paez
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You TestSchalk Cronjé
 

Similar to 15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp) (20)

Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
Rc2010 tdd
Rc2010 tddRc2010 tdd
Rc2010 tdd
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Android testing
Android testingAndroid testing
Android testing
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_test
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
Pitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz BankowskiPitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz Bankowski
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
 
Introduction to Voice I/O on Android
Introduction to Voice I/O on AndroidIntroduction to Voice I/O on Android
Introduction to Voice I/O on Android
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Mockito intro
Mockito introMockito intro
Mockito intro
 

More from Danny Preussler

We aint got no time - Droidcon Nairobi
We aint got no time - Droidcon NairobiWe aint got no time - Droidcon Nairobi
We aint got no time - Droidcon NairobiDanny Preussler
 
Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Danny Preussler
 
TDD on android. Why and How? (Coding Serbia 2019)
TDD on android. Why and How? (Coding Serbia 2019)TDD on android. Why and How? (Coding Serbia 2019)
TDD on android. Why and How? (Coding Serbia 2019)Danny Preussler
 
TDD on Android (Øredev 2018)
TDD on Android (Øredev 2018)TDD on Android (Øredev 2018)
TDD on Android (Øredev 2018)Danny Preussler
 
Junit5: the next gen of testing, don't stay behind
Junit5: the next gen of testing, don't stay behindJunit5: the next gen of testing, don't stay behind
Junit5: the next gen of testing, don't stay behindDanny Preussler
 
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016Danny Preussler
 
All around the world, localization and internationalization on Android (Droid...
All around the world, localization and internationalization on Android (Droid...All around the world, localization and internationalization on Android (Droid...
All around the world, localization and internationalization on Android (Droid...Danny Preussler
 
(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016
(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016
(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016Danny Preussler
 
Unit testing on Android (Droidcon Dubai 2015)
Unit testing on Android (Droidcon Dubai 2015)Unit testing on Android (Droidcon Dubai 2015)
Unit testing on Android (Droidcon Dubai 2015)Danny Preussler
 
Clean code on Android (Droidcon Dubai 2015)
Clean code on Android (Droidcon Dubai 2015)Clean code on Android (Droidcon Dubai 2015)
Clean code on Android (Droidcon Dubai 2015)Danny Preussler
 
More android code puzzles
More android code puzzlesMore android code puzzles
More android code puzzlesDanny Preussler
 
Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014
Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014
Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014Danny Preussler
 
Abgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, Berlin
Abgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, BerlinAbgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, Berlin
Abgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, BerlinDanny Preussler
 
Rockstar Android Testing (Mobile TechCon Munich 2014)
Rockstar Android Testing (Mobile TechCon Munich 2014)Rockstar Android Testing (Mobile TechCon Munich 2014)
Rockstar Android Testing (Mobile TechCon Munich 2014)Danny Preussler
 
Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)Danny Preussler
 

More from Danny Preussler (15)

We aint got no time - Droidcon Nairobi
We aint got no time - Droidcon NairobiWe aint got no time - Droidcon Nairobi
We aint got no time - Droidcon Nairobi
 
Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)
 
TDD on android. Why and How? (Coding Serbia 2019)
TDD on android. Why and How? (Coding Serbia 2019)TDD on android. Why and How? (Coding Serbia 2019)
TDD on android. Why and How? (Coding Serbia 2019)
 
TDD on Android (Øredev 2018)
TDD on Android (Øredev 2018)TDD on Android (Øredev 2018)
TDD on Android (Øredev 2018)
 
Junit5: the next gen of testing, don't stay behind
Junit5: the next gen of testing, don't stay behindJunit5: the next gen of testing, don't stay behind
Junit5: the next gen of testing, don't stay behind
 
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
 
All around the world, localization and internationalization on Android (Droid...
All around the world, localization and internationalization on Android (Droid...All around the world, localization and internationalization on Android (Droid...
All around the world, localization and internationalization on Android (Droid...
 
(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016
(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016
(Android) Developer Survival in Multiscreen World, MobCon Sofia 2016
 
Unit testing on Android (Droidcon Dubai 2015)
Unit testing on Android (Droidcon Dubai 2015)Unit testing on Android (Droidcon Dubai 2015)
Unit testing on Android (Droidcon Dubai 2015)
 
Clean code on Android (Droidcon Dubai 2015)
Clean code on Android (Droidcon Dubai 2015)Clean code on Android (Droidcon Dubai 2015)
Clean code on Android (Droidcon Dubai 2015)
 
More android code puzzles
More android code puzzlesMore android code puzzles
More android code puzzles
 
Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014
Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014
Bye Bye Charles, Welcome Odo, Android Meetup Berlin May 2014
 
Abgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, Berlin
Abgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, BerlinAbgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, Berlin
Abgeschottete Realität - Testen im Emulator, Mobile Testing Days 2014, Berlin
 
Rockstar Android Testing (Mobile TechCon Munich 2014)
Rockstar Android Testing (Mobile TechCon Munich 2014)Rockstar Android Testing (Mobile TechCon Munich 2014)
Rockstar Android Testing (Mobile TechCon Munich 2014)
 
Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)
 

Recently uploaded

SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 

Recently uploaded (20)

SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 

15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)

  • 1. 15 tips to improve your unit tests Droidcon 2016 Barcamp @PreusslerBerlin
  • 2. What makes a clean test? Three things. Readability, readability, and readability Uncle Bob, Clean Code
  • 3. #1 Don‘t start your test methods with „test“ • That‘s Junit3 way • Junit4 was released 10 years ago! • Prevents good method names @Test public void should_stop_sync_if_error()
  • 4. #2 Have consistent naming • Have one name for the instance under test Don‘t let the reader guess which class is tested public class MessageTest { Parcel parcel = mock(Parcel.class); Message tested = new Message("subject", “text“); @Test public void should_write_to_parcel() { tested.writeToParcel(parcel, 0); ...
  • 5. #3 Don‘t use pure junit asserts! • Nobody remembers actual and expected order • Hamcrest matchers: • FEST assertions: assertThat(yoda).isInstanceOf(Jedi.class) .isEqualTo(foundJedi) .isNotEqualTo(foundSith); assertThat("test", anyOf(is("testing"), containsString("est")));
  • 6. #4 The test method is the most import part • Move as much code out of test as possible to setup or init-block • 90% of readers won‘t need that @Test public void should_not_be_empty() { when(login.isLoggedIn()).thenReturn(true); when(options.showDashboardValues()).thenReturn(true); assertFalse(tested.isEmptyDashboardShown()); }
  • 7. #4 The test method is the most import part • Move as much code out of test as possible to setup or init-block • 90% of readers won‘t need that @Before public void setup() { login = mock(Login.class); when(login.isLoggedIn()).thenReturn(true); options = mock(DisplayOptions.class); displayUtil = mock(DisplayUtil.class); when(options.showDashboardValues()).thenReturn(true); tested = new ContentFragmentBuilderPhone(login, options, displayUtil); }
  • 8. #4 The test method is the most import part • Move as much code out of test as possible to setup or init-block • Don‘t do both: Place place = new Place("1", "one", Location.NONE); Merchant merchant1 = new Merchant("1", "one", MerchantAccessLevel.FULL_ACCESS); Merchant merchant2 = new Merchant("2", "two", MerchantAccessLevel.FULL_ACCESS); PlaceListTabletFragment tested = spy(new PlaceListTabletFragment()); @Before public void setup() { tested.places = new Places(Arrays.asList(place)); tested.merchant = merchant1; tested.interactor = mock(LoginInteractor.class); tested.loggedInUser = new LoggedInUser(NO_USER,NO_TOKEN, Arrays.asList(merchant1, merchant2), NO_PLACE); }
  • 9. #5 No javadoc to explain the test steps @Test public void testGetParentScope_shouldReturnRootScope_whenAskedForSingleton() { //GIVEN Scope parentScope = Toothpick.openScope("root"); Scope childScope = Toothpick.openScopes("root", "child"); //WHEN Scope scope = childScope.getParentScope(Singleton.class); //THEN assertThat(scope, is(parentScope)); } #1 #4
  • 10. Scope parentScope = Toothpick.openScope("root"); Scope childScope = Toothpick.openScopes("root", "child"); @Test public void should_return_root_scope () { Scope scope = childScope.getParentScope(Singleton.class); assertThat(scope, is(parentScope)); } #5 No javadoc to explain the test steps
  • 11. #6 Reduce the noise: readability first • No finals, nor private fields • No final on methods or variables • Test instances don‘t see each other it is safe to violate encapsulation in tests! private final Place place = new Place("1", "one“); private final Merchant merchant = new Merchant("1", "one“);
  • 12. #7 Always implement equals! Keeps test short and readable assertThat(tested.getUser()) .isEqualTo(new User(“danny”));
  • 13. #8 Add matcher for your models • anyDeal() instead of any(Deal.class) • mockDeal() instead of mock(Deal.class) • For android check out github.com/dpreussler/mockitoid
  • 14. #9 Use the Null-Object pattern • Prefer Optionals over null • Prefer Null-Object over optionals • Prefer Null-Object over mocks as mocks dont respect nonnull contract • Often in tests you just need the right type, not a specific new instance -> reduce test garbage tested.redeem(Deal.NO_DEAL, mock(EventBus.class));
  • 15. #10 Have default implemenations @Singleton public class UiFlavors { public static final UiFlavors TABLET = new UiFlavors(true); public static final UiFlavors PHONE = new UiFlavors(false); private final boolean isTablet; @Inject public UiFlavors(Resources resources) { this(detectTablet(resources)); } ... Filled on runtime For tests and equal checks
  • 16. #10 Have default implemenations @Singleton public class UiFlavors { public static final UiFlavors TABLET = new UiFlavors(true); public static final UiFlavors PHONE = new UiFlavors(false); private final boolean isTablet; @Inject public UiFlavors(Resources resources) { this(detectTablet(resources)); } ... @Test public void should_add_custom_dimension_for_phone() { TrackingImpl tested = new TrackingImpl(UiFlavors.PHONE, mockContext()); tested.setCustomDimensions(eventBuilder); verify(eventBuilder).setCustomDimension(1, "phone"); }
  • 17. #11 Write readable Reflection code SuperReflect.on( Build.VERSION.class) .set("SDK_INT", 14); Fluent interface, good for setting values (incl. finals) in API/ 3rd party/ code github.com/dpreussler/SuperReflect SuperReflect.on(tested) .get(“privateField“);
  • 18. #11 Write readable Reflection code @BoundBox( boundClass = A.class ) private BoundBoxOfA tested; @Test public void test() { tested = new BoundBoxOfA( new A("bb") ); tested.boundbox_privateField() } Generate getters for private fields (compiletime-safe) github.com/stephanenicolas/boundbox
  • 19. #12 Don‘t be too strict on „units“ Real world API JSON parsing and conversion to models is a large unit but very useful test @Test public void can_read_from_json() throws IOException { String values = inputStreamToString(JsonDealsTest.class.getResourceAsStream(“/deals.json")); JsonDeals out = new Gson().fromJson(values, JsonDeals.class); List<Deal> deals= out.asDealList(); assertThat (deals.get(0).getTitle()).isEqualTo(“First TestTitle“); }
  • 20. #13 If you can not test, then it‘s not good code Do you know the rule about encapsulation and tests? Uh, no. What rule is that? Tests trump Encapsulation. What does that mean? That means that tests win. No test can be denied access to a variable simply to maintain encapsulation. Uncle Bob (https://blog.8thlight.com/uncle-bob/2015/06/30/the-little-singleton.html)
  • 21. #14 Inversion of Control If you create objects (especially views) in a constructor, overload another constructor for testing public OptionsViewHolder(View itemView) { this(itemView, new DealAnalyticsView(itemView, formatter)); } @VisibleForTesting OptionsViewHolder(View itemView, DealAnalyticsView analyticsView){ ...
  • 22. #15 Make it fail! The pupil went to the master programmer and said: “All my tests pass all the time. Don’t I deserve a raise?” The master slapped the pupil and replied: “If all your tests pass, all the time, you need to write better tests.” Good tests fail The Way of Testivus, Alberto Savoia http://www.agitar.com/downloads/TheWayOfTestivus.pdf
  • 23. Unit testing is no rocket science! @PreusslerBerlin Thank you!

Editor's Notes

  1. Todo make same example
  2. Try to keep test to max 3 lines
  3. Try to keep test to max 3 lines
  4. Try to keep test to max 3 lines
  5. YES its fine to use reflection