SlideShare a Scribd company logo
1 of 28
Download to read offline
Hazem Saleh
Software Architect, @ Viacom, New York
§ More than fifteen years of experience in software development.
§ Apache Open Source Committer and PMC member.
§ Author of five technical books (One of them is a best selling).
§ DeveloperWorks Contributing Author.
§ Medium Android blogger.
§ DZone MVB.
§ Technical Speaker (Droidcon, AnDevCon, ApacheCon, Geecon,
JavaOne, JavaLand, …etc).
§ An X-IBMer and Currently a Software Architect in Viacom.
§ Challenges of Mockito 1.x.
§ Demo – Mockito 1.x Challenges.
§ Mockito 2.x advantages.
§ Tips and Tricks for Migrating Mockito 1.x unit tests to
Mockito 2.x.
§ Mockito 2.x migrated tests demos:
§ Mocking Final classes and methods.
§ Mocking Third party static method APIs.
§ What about Kotlin?
§ Demo – Kotlin Mockito.
§ Conclusion.
§ Mocking final methods was not
supported.
§ Mocking final classes was not
supported.
Typical Exception when you try to mock final classes or methods
• To overcome these issues in Mockito 1.x, we needed
to use PowerMock, we have to:
• Change our class runner to PowerMockRunner.
• Prepare the classes that contains final/static
methods for testing.
• Do some extra calls, for example to:
• To mock your intended class using
PowerMockito.mock(yourClass.class).
• To verify static methods, make a call to
PowerMockito.verifyStatic().
• Using PowerMock is not for free, it adds an extra
overhead on the performance of unit tests.
GitHub Repo:
https://github.com/hazems/android-demo-app/tree/mockito1x
§ Mocking final methods is
supported.
§ Mocking final classes is
supported.
§ Java 8 is supported.
§ Migration from CGLIB to
ByteBuddy.
§ Unfortunately, migration from Mockito 1.x to Mockito 2.x is
not an easy task.
§ If you have a large number of unit tests, migrating your unit
tests to Mockito 2.x will most probably a painful task
because Mockito 2.x does not respect some of the old
behaviors of Mockito 1.x.
§ Adding to this complexity, If you are using PowerMock in
your old tests, then you will have to face another dimension
of complexity since most of PowerMock’s versions are
having integration issues with Mockito 2.x.
§ In the beginning when just changing Mockito version to 2.x
in build.gradle file of a project with tons of unit tests, I
found more than 50% of unit tests were failing due to many
issues:
§ Null pointer exceptions.
§ Compilation errors.
§ No class definition found exceptions.
§ Other un-expected thrown exceptions.
§ In order to overcome these issues, the following steps are
applied to successfully migrate unit tests to Mockito 2.x.
§ Never forget to always use org.mockito.ArgumentMatchers
instead of the old org.mockito.Matchers.
§ This can fail many unit tests, In Mockito 2.x, anyString()
does not match null anymore.
§ To solve this problem:
§ Review if your old failing unit tests really intended to assert
nulls. If your unit test is intended to assert null, then simply
replace anyString() with an actual null value.
§ If your unit test is NOT intended to assert null (and was
intended to assert an actual value), then
§ Rewrite your unit test because it was previously not implemented
in a right way.
§ Rewrite here should make sure to return the intended non-null
value to be asserted.
MessageHandler::handle() MessageProcessor::process() MessageFormatter::format()
MessageHandler::handle() MessageProcessor::process() MessageFormatter::format()
In Mockito 2.x,
This will fail since
anyString() != null
This works in
Mockito 1.x.
MessageHandler::handle() MessageProcessor::process() MessageFormatter::format()
Now, format() is properly verified
Mock dependencies properly
• This works in
Mockito 2.x.
• Mockito 2.x
reveals some of
incomplete
written unit tests
that was written in
Mockito 1.x.
§After the upgrade, you may find anyInt() does not
work because it cannot match long literals such as
0L or 10L.
§To solve this problem:
§Replace anyInt() with anyLong().
§Replace anyInt() with the actual long value.
§ If your old tests use
org.mockito.internal.util.reflection.Whitebox, Do not be
surprised when your unit tests fail.
§ Whitebox is removed from Mockito 2.x.
§ Using Whitebox at first place is a bad testing practice and an
indicator for code testability problem.
§ To solve this problem, you have the following options:
§ (Recommended) Refactor these failing tests for avoiding
using Whitebox (this may require actual code refactoring to
allow testability).
§ (I do not like)You can use PowerMock
(org.powermock.reflect.Whitebox).
§getArgumentAt() is removed from
InvocationOnMock, the following line will not
compile in Mockito 2.x.
§Using powermock-api-mockito extension does not
work with Mockito 2.x, you will have the following
exception when running your unit tests
In order to fix this issue,
you should use the new
right Mockito’s 2.x API
extension which is
powermock-api-mockito2.
§ Mockito 2.x is not a real friend to PowerMock.
§ Always make sure to use compatible versions of PowerMock with
Mockito.
§ For example, if you use PowerMock 1.6.5 or even PowerMock
1.7.0RC2 with Mockito 2.7.1, you will find the following exception
with Mockito donothing() API (To solve it, you need to use
PowerMock 1.7.0RC4).
§As shown in the previous two tips, there are multiple
problems of using PowerMock with Mockito 2.x.
§We find it beneficial to move away incrementally
from PowerMock and only depend on Mockito 2.x.
§How to get rid of PowerMock:
§ Using Wrapper Proxy pattern (to be explained in Demo).
§ Although this tip is not directly
related to migration but I think it is
important.
§ Take the migration task as a chance
to review your project unit tests.
§ Try to allocate enough time to:
§ Fix flacky unit tests.
§ Remove or fix ignored unit tests.
GitHub Repo:
https://github.com/hazems/android-demo-app/tree/mockito2x
§ There are certain situations in which you have to deal with
Third party APIs that are static.
§ In order to mock static API in your unit tests, you will have
to use PowerMock!
§ As shown in Tip #8, it is always recommended to just use
Mockito 2.x without PowerMock, so how can we solve this
issue.
§ One of the ideas that can help is to:
§ Create a Wrapper Proxy class for every class having static
methods to provide non-static testable APIs.
§ Remove all direct references to all classes with static methods,
and use the new Wrapper Proxy classes instead.
GitHub Repo:
https://github.com/hazems/android-demo-app/tree/mockito2x
§ Mockito currently works fine with Kotlin,
but the syntax is not optimal.
§ A small tip here to have the best
integration experience is to use
Mockito Kotlin:
https://github.com/nhaarman/mockito-
kotlin
§ Mockito Kotlin provides a nice syntactic
sugar in Mockito for Kotlin projects.
§ In Addition,You can use Kluent. Kluent is a
"Fluent Assertions" library written
specifically for Kotlin:
https://github.com/MarkusAmshove/Kluent
Method name can be
`doAction(), does something`
Inline mocking
assertEquals(“Hello World”, result)
result `should equal` “Hello World”
GitHub Repo:
https://github.com/hazems/android-demo-app/tree/migrate_kotlin
§ Mockito 1.x has some challenges such as the in-ability of
mocking final classes, and methods.
§ Mockito 2.x solved many of the challenges in Mockito 1.x,
so it is really worth the migration effort.
§ Applying the tips mentioned in this presentation can
facilitate migrating unit tests from Mockito 1.x to Mockito
2.x.
§ Using Wrapper Proxy Pattern and Mockito 2.x framework
can allow you to get rid of PowerMock.
Blog: https://medium.com/@hazems
Twitter: @hazems

More Related Content

What's hot

TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019Paulo Clavijo
 
Lessons learned on software testing automation
Lessons learned on software testing automationLessons learned on software testing automation
Lessons learned on software testing automationgaoliang641
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinSigma Software
 
Programming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStringsProgramming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStringsAlan Richardson
 
Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#Paul Houle
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOSPablo Villar
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018Paulo Clavijo
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentjakubkoci
 
ES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game KataES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game KataDavid Rodenas
 
Robolectric android taipei
Robolectric   android taipeiRobolectric   android taipei
Robolectric android taipeiRichard Chang
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practicesMarian Wamsiedel
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 
Cpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp EuropeCpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp EuropeClare Macrae
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffectiveUI
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffective
 

What's hot (20)

TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019
 
Java bad coding practices
Java bad coding practicesJava bad coding practices
Java bad coding practices
 
Lessons learned on software testing automation
Lessons learned on software testing automationLessons learned on software testing automation
Lessons learned on software testing automation
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita Galkin
 
Programming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStringsProgramming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStrings
 
Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
ES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game KataES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game Kata
 
Robolectric android taipei
Robolectric   android taipeiRobolectric   android taipei
Robolectric android taipei
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practices
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Cpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp EuropeCpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp Europe
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 

Similar to Mockito 2.x Migration - Droidcon UK 2018

[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScriptHazem Saleh
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing trainingTom Tang
 
Magento code testability: Problems and Solutions
Magento code testability: Problems and SolutionsMagento code testability: Problems and Solutions
Magento code testability: Problems and SolutionsAnton Kril
 
Agile principles and practices
Agile principles and practicesAgile principles and practices
Agile principles and practicesVipin Jose
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practicesfloydophone
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxVictor Rentea
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etcYaron Karni
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit7mind
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and backDavid Rodenas
 
AOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java PlatformAOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java PlatformPeter Pilgrim
 
Neoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocksguillaumecarre
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applicationsBabak Naffas
 

Similar to Mockito 2.x Migration - Droidcon UK 2018 (20)

Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing training
 
Magento code testability: Problems and Solutions
Magento code testability: Problems and SolutionsMagento code testability: Problems and Solutions
Magento code testability: Problems and Solutions
 
Agile principles and practices
Agile principles and practicesAgile principles and practices
Agile principles and practices
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
 
(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
AOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java PlatformAOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java Platform
 
Neoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injection
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
 

More from Hazem Saleh

JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101Hazem Saleh
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for AndroidHazem Saleh
 
[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache Cordova[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache CordovaHazem Saleh
 
[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In ActionHazem Saleh
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In ActionHazem Saleh
 
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache CordovaHazem Saleh
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache CordovaHazem Saleh
 
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014Hazem Saleh
 
Dojo >= 1.7 Kickstart
Dojo >= 1.7  KickstartDojo >= 1.7  Kickstart
Dojo >= 1.7 KickstartHazem Saleh
 
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013Hazem Saleh
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Hazem Saleh
 
JSF Mashups in Action
JSF Mashups in ActionJSF Mashups in Action
JSF Mashups in ActionHazem Saleh
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Hazem Saleh
 
JavaScript tools
JavaScript toolsJavaScript tools
JavaScript toolsHazem Saleh
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Hazem Saleh
 
[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise Java[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise JavaHazem Saleh
 

More from Hazem Saleh (17)

JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android
 
[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache Cordova[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache Cordova
 
[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In Action
 
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
 
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
 
Dojo >= 1.7 Kickstart
Dojo >= 1.7  KickstartDojo >= 1.7  Kickstart
Dojo >= 1.7 Kickstart
 
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013
 
JSF Mashups in Action
JSF Mashups in ActionJSF Mashups in Action
JSF Mashups in Action
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013
 
JavaScript tools
JavaScript toolsJavaScript tools
JavaScript tools
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
 
[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise Java[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise Java
 
GMaps4JSF
GMaps4JSFGMaps4JSF
GMaps4JSF
 

Mockito 2.x Migration - Droidcon UK 2018

  • 1. Hazem Saleh Software Architect, @ Viacom, New York
  • 2. § More than fifteen years of experience in software development. § Apache Open Source Committer and PMC member. § Author of five technical books (One of them is a best selling). § DeveloperWorks Contributing Author. § Medium Android blogger. § DZone MVB. § Technical Speaker (Droidcon, AnDevCon, ApacheCon, Geecon, JavaOne, JavaLand, …etc). § An X-IBMer and Currently a Software Architect in Viacom.
  • 3. § Challenges of Mockito 1.x. § Demo – Mockito 1.x Challenges. § Mockito 2.x advantages. § Tips and Tricks for Migrating Mockito 1.x unit tests to Mockito 2.x. § Mockito 2.x migrated tests demos: § Mocking Final classes and methods. § Mocking Third party static method APIs. § What about Kotlin? § Demo – Kotlin Mockito. § Conclusion.
  • 4. § Mocking final methods was not supported. § Mocking final classes was not supported. Typical Exception when you try to mock final classes or methods
  • 5. • To overcome these issues in Mockito 1.x, we needed to use PowerMock, we have to: • Change our class runner to PowerMockRunner. • Prepare the classes that contains final/static methods for testing. • Do some extra calls, for example to: • To mock your intended class using PowerMockito.mock(yourClass.class). • To verify static methods, make a call to PowerMockito.verifyStatic(). • Using PowerMock is not for free, it adds an extra overhead on the performance of unit tests.
  • 7. § Mocking final methods is supported. § Mocking final classes is supported. § Java 8 is supported. § Migration from CGLIB to ByteBuddy.
  • 8. § Unfortunately, migration from Mockito 1.x to Mockito 2.x is not an easy task. § If you have a large number of unit tests, migrating your unit tests to Mockito 2.x will most probably a painful task because Mockito 2.x does not respect some of the old behaviors of Mockito 1.x. § Adding to this complexity, If you are using PowerMock in your old tests, then you will have to face another dimension of complexity since most of PowerMock’s versions are having integration issues with Mockito 2.x.
  • 9. § In the beginning when just changing Mockito version to 2.x in build.gradle file of a project with tons of unit tests, I found more than 50% of unit tests were failing due to many issues: § Null pointer exceptions. § Compilation errors. § No class definition found exceptions. § Other un-expected thrown exceptions. § In order to overcome these issues, the following steps are applied to successfully migrate unit tests to Mockito 2.x.
  • 10. § Never forget to always use org.mockito.ArgumentMatchers instead of the old org.mockito.Matchers.
  • 11. § This can fail many unit tests, In Mockito 2.x, anyString() does not match null anymore. § To solve this problem: § Review if your old failing unit tests really intended to assert nulls. If your unit test is intended to assert null, then simply replace anyString() with an actual null value. § If your unit test is NOT intended to assert null (and was intended to assert an actual value), then § Rewrite your unit test because it was previously not implemented in a right way. § Rewrite here should make sure to return the intended non-null value to be asserted.
  • 13. MessageHandler::handle() MessageProcessor::process() MessageFormatter::format() In Mockito 2.x, This will fail since anyString() != null This works in Mockito 1.x.
  • 14. MessageHandler::handle() MessageProcessor::process() MessageFormatter::format() Now, format() is properly verified Mock dependencies properly • This works in Mockito 2.x. • Mockito 2.x reveals some of incomplete written unit tests that was written in Mockito 1.x.
  • 15. §After the upgrade, you may find anyInt() does not work because it cannot match long literals such as 0L or 10L. §To solve this problem: §Replace anyInt() with anyLong(). §Replace anyInt() with the actual long value.
  • 16. § If your old tests use org.mockito.internal.util.reflection.Whitebox, Do not be surprised when your unit tests fail. § Whitebox is removed from Mockito 2.x. § Using Whitebox at first place is a bad testing practice and an indicator for code testability problem. § To solve this problem, you have the following options: § (Recommended) Refactor these failing tests for avoiding using Whitebox (this may require actual code refactoring to allow testability). § (I do not like)You can use PowerMock (org.powermock.reflect.Whitebox).
  • 17. §getArgumentAt() is removed from InvocationOnMock, the following line will not compile in Mockito 2.x.
  • 18. §Using powermock-api-mockito extension does not work with Mockito 2.x, you will have the following exception when running your unit tests In order to fix this issue, you should use the new right Mockito’s 2.x API extension which is powermock-api-mockito2.
  • 19. § Mockito 2.x is not a real friend to PowerMock. § Always make sure to use compatible versions of PowerMock with Mockito. § For example, if you use PowerMock 1.6.5 or even PowerMock 1.7.0RC2 with Mockito 2.7.1, you will find the following exception with Mockito donothing() API (To solve it, you need to use PowerMock 1.7.0RC4).
  • 20. §As shown in the previous two tips, there are multiple problems of using PowerMock with Mockito 2.x. §We find it beneficial to move away incrementally from PowerMock and only depend on Mockito 2.x. §How to get rid of PowerMock: § Using Wrapper Proxy pattern (to be explained in Demo).
  • 21. § Although this tip is not directly related to migration but I think it is important. § Take the migration task as a chance to review your project unit tests. § Try to allocate enough time to: § Fix flacky unit tests. § Remove or fix ignored unit tests.
  • 23. § There are certain situations in which you have to deal with Third party APIs that are static. § In order to mock static API in your unit tests, you will have to use PowerMock! § As shown in Tip #8, it is always recommended to just use Mockito 2.x without PowerMock, so how can we solve this issue. § One of the ideas that can help is to: § Create a Wrapper Proxy class for every class having static methods to provide non-static testable APIs. § Remove all direct references to all classes with static methods, and use the new Wrapper Proxy classes instead.
  • 25. § Mockito currently works fine with Kotlin, but the syntax is not optimal. § A small tip here to have the best integration experience is to use Mockito Kotlin: https://github.com/nhaarman/mockito- kotlin § Mockito Kotlin provides a nice syntactic sugar in Mockito for Kotlin projects. § In Addition,You can use Kluent. Kluent is a "Fluent Assertions" library written specifically for Kotlin: https://github.com/MarkusAmshove/Kluent Method name can be `doAction(), does something` Inline mocking assertEquals(“Hello World”, result) result `should equal` “Hello World”
  • 27. § Mockito 1.x has some challenges such as the in-ability of mocking final classes, and methods. § Mockito 2.x solved many of the challenges in Mockito 1.x, so it is really worth the migration effort. § Applying the tips mentioned in this presentation can facilitate migrating unit tests from Mockito 1.x to Mockito 2.x. § Using Wrapper Proxy Pattern and Mockito 2.x framework can allow you to get rid of PowerMock.