SlideShare a Scribd company logo
7 Stages of Unit
Testing in Android
Jorge D. Ortiz Fuentes
@jdortiz
#7SUnitTest
A POWWAU
production
#7SUnitTest
#7SUnitTest
Daring as a fool
★ Speaking from the shoulders of giants.
Look up here!
★ This is not UnitTesting 101, but
complementary to it
1.
Shock & Disbelief
But my code is
always awesome!
#7SUnitTest
Unit Tests
★ Prove correctness of different aspects of the
public interface.
• Prove instead of intuition
• Define contract and assumptions
• Document the code
• Easier refactoring or change
★ Reusable code = code + tests
#7SUnitTest
Use Unit Testing
Incrementally
★ You don’t have to write every unit test
★ Start with the classes that take care of the
logic
• If mixed apply SOLID
★ The easier entry point are bugs
2.
Denial
C’mon, it takes
ages to write
tests!
Time writing tests <
Time debugging
#7SUnitTest
Good & Bad News
★ Most things are already available in Android Studio
★ Projects are created with
• test package
• ApplicationTest class
★ It requires some tweaking
★ Google docs are for Eclipse
• modules instead of projects
• different UI…
OTS functionality
JUnit
AssertTestCase
AndroidTestCase
TestSuite
ApplicationTestCase
InstrumentationTes
tCase
ActivityInstrumenta
tionTestCase2
junit.framework
Run from IDE
Run in
(V)Device
3.
Anger
How do I write
those f***ing
tests?
#7SUnitTest
Types of Unit Tests
★ Test return value
★ Test state
★ Test behavior
public class TaskTests extends TestCase {
final static String TASK_NAME = "First task";
final static String TASK_DONE_STRING = "First task:
Done";
final static String TASK_NOT_DONE_STRING = "First
task: NOT done";
Task mTask;
@Override
public void setUp() throws Exception { super.setUp();
mTask = new Task(); }
@Override
public void tearDown() throws Exception
{ super.tearDown();
mTask = null; }
public void testDoneStatusIsDisplayedProperly()
throws Exception {
mTask.setName(TASK_NAME);
mTask.setDone(true);
String taskString = mTask.toString();
assertEquals("String must be "taskname: Done"",
TASK_DONE_STRING, taskString);
}
public void testNotDoneStatusIsDisplayedProperly()
throws Exception {
mTask.setName(TASK_NAME);
mTask.setDone(false);
assertEquals("String must be "taskname: NOT done
"", TASK_NOT_DONE_STRING, mTask.toString()); } }
Example
public class Task {
private String mName;
private Boolean mDone;
public String getName() { return
mName; }
public void setName(String name)
{ mName = name; }
}
public Boolean getDone() { return
mDone; }
public void setDone(Boolean done) {
mDone = done;
}
@Override
public String toString() {
return mName + ": " +
(mDone?"Done":"NOT done");
}
}
public class ModelAndLogicTestSuite
extends TestSuite {
public static Test suite() {
return new
TestSuiteBuilder(ModelAndLogicTestS
uite.class)
.includePackages(“c
om.powwau.app.interactor”,
“com.powwau.app.data”)
.build();
}
public ModelAndLogicTestSuite()
{
super();
}
}
Running more than one
TestCase
public class FullTestSuite
extends TestSuite {
public static Test suite() {
return new
TestSuiteBuilder(FullTestSuite.cl
ass)
.includeAllPackag
esUnderHere()
.build();
}
public FullTestSuite() {
super();
}
}
Instrumentation Tests
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
Activity mActivity;
public MainActivityUnitTest() {
super(MainActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
}
public void testHelloIsDisplayed() throws Exception {
onView(withText(“Hello world!")).check(ViewAssertions.matches(isDisplayed()));
}
public void testSalutationChangesWithButtonClick() throws Exception {
onView(withText("Touch Me")).perform(click());
onView(withText("Bye bye,
Moon!”)).check(ViewAssertions.matches(isDisplayed()));
}
}
4.
Bargain
Ok, I’ll write
some tests, but
make my life
simpler
#7SUnitTest
Dependency Injection
★ Control behavior of the dependencies
• Constructor
• Method overwriting
• Property injection:Lazy instantiation
★ Or use a DI framework: Dagger 2
Dependency Injection
for Poor Developers
public void preserveUserName(String name)
{
SharedPreferences prefs =
getPreferences(“appPrefs”,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor =
prefs.edit();
editor.putString(USER_NAME_KEY, name);
editor.commit();
}
Dependency Injection
for Poor Developers
public void preserveUserName(String name) {
SharedPreferences prefs = getAppPrefs();
SharedPreferences.Editor editor = prefs.edit();
editor.putString(USER_NAME_KEY, name);
editor.commit();
}
SharedPreferences getAppPrefs() {
if (mAppPrefs == null) {
mAppPrefs = getPreferences(“appPrefs”,
Context.MODE_PRIVATE);
}
return mAppPrefs;
}
DataRepo dataRepoMock = mock(DataRepo.class);
when(dataRepoMock.existsObjWithId(23)).thenReturn(
true);
verify(dataRepoMock).deleteObjWithId(23);
Simulating and Testing
Behavior
★ Stubs & Mocks
• Both are fake objects
• Stubs provide desired responses to the SUT
• Mocks also expect certain behaviors
5.
Guilt
But this ain’t
state of the art
#7SUnitTest
Problems so far
★ Tests run in (v)device: slow
★ Unreliable behavior:
• Command line
• Integration with mocking
6.
Depression
My tests are
never good
enough!
#7SUnitTest
Use JUnit 4
★ Don’t extend TestCase
★ Don’t start with test (@Test instead)
★ @Before & @After instead of setUp and
tearDown. Also for the class
★ @ignore
★ Exceptions & timeouts (@Test params)
★ @Theory & @DataPoints
Gradle config
sourceSets {
test.setRoot(“src/test”)
}
dependencies {
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.9.5'
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'org.mockito:mockito-
core:1.9.5'
}
How to Use JUnit 4
#7SUnitTest
CLI-aware Also
★ ./gradlew check
• lint
• test
★ Open app/build/reports/tests/debug/
index.html
7.
Acceptance &
Hope
No tests, no fun
#7SUnitTest
Evolve
★ Clean Architecture
★ TDD
★ Functional tests :monkeyrunner
★ CI (Jenkins)
Thank
you!
@jdortiz
#7SUnitTest

More Related Content

What's hot

Software Engineering- Types of Testing
Software Engineering- Types of TestingSoftware Engineering- Types of Testing
Software Engineering- Types of TestingTrinity Dwarka
 
Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Damian T. Gordon
 
Types of software testing
Types of software testingTypes of software testing
Types of software testingTestbytes
 
Software Testing Fundamentals | Basics Of Software Testing
Software Testing Fundamentals | Basics Of Software TestingSoftware Testing Fundamentals | Basics Of Software Testing
Software Testing Fundamentals | Basics Of Software TestingKostCare
 
software testing methodologies
software testing methodologiessoftware testing methodologies
software testing methodologiesJhonny Jhon
 
Software Testing
Software TestingSoftware Testing
Software TestingKiran Kumar
 
Types of Software Testing
Types of Software TestingTypes of Software Testing
Types of Software TestingNishant Worah
 
SOFTWARE TESTING UNIT-4
SOFTWARE TESTING UNIT-4  SOFTWARE TESTING UNIT-4
SOFTWARE TESTING UNIT-4 Mohammad Faizan
 
Software Testing Tutorials - MindScripts Technologies, Pune
Software Testing Tutorials - MindScripts Technologies, PuneSoftware Testing Tutorials - MindScripts Technologies, Pune
Software Testing Tutorials - MindScripts Technologies, Punesanjayjadhav8789
 
Software quality and testing (func. &amp; non func.)
Software quality and testing (func. &amp; non   func.)Software quality and testing (func. &amp; non   func.)
Software quality and testing (func. &amp; non func.)Pragya G
 

What's hot (20)

Software Engineering- Types of Testing
Software Engineering- Types of TestingSoftware Engineering- Types of Testing
Software Engineering- Types of Testing
 
Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)
 
Software testing
Software testingSoftware testing
Software testing
 
Types of software testing
Types of software testingTypes of software testing
Types of software testing
 
Testing methodology
Testing methodologyTesting methodology
Testing methodology
 
Software Testing Fundamentals | Basics Of Software Testing
Software Testing Fundamentals | Basics Of Software TestingSoftware Testing Fundamentals | Basics Of Software Testing
Software Testing Fundamentals | Basics Of Software Testing
 
Transactionflow
TransactionflowTransactionflow
Transactionflow
 
software testing methodologies
software testing methodologiessoftware testing methodologies
software testing methodologies
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Types of Software Testing
Types of Software TestingTypes of Software Testing
Types of Software Testing
 
Testing fundamentals
Testing fundamentalsTesting fundamentals
Testing fundamentals
 
3.software testing
3.software testing3.software testing
3.software testing
 
System testing
System testingSystem testing
System testing
 
SOFTWARE TESTING UNIT-4
SOFTWARE TESTING UNIT-4  SOFTWARE TESTING UNIT-4
SOFTWARE TESTING UNIT-4
 
Software Testing Tutorials - MindScripts Technologies, Pune
Software Testing Tutorials - MindScripts Technologies, PuneSoftware Testing Tutorials - MindScripts Technologies, Pune
Software Testing Tutorials - MindScripts Technologies, Pune
 
Software testing methods
Software testing methodsSoftware testing methods
Software testing methods
 
Software Testing or Quality Assurance
Software Testing or Quality AssuranceSoftware Testing or Quality Assurance
Software Testing or Quality Assurance
 
Software quality and testing (func. &amp; non func.)
Software quality and testing (func. &amp; non   func.)Software quality and testing (func. &amp; non   func.)
Software quality and testing (func. &amp; non func.)
 
Types of testing
Types of testingTypes of testing
Types of testing
 
System testing
System testingSystem testing
System testing
 

Similar to 7 stages of unit testing

7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOSJorge Ortiz
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
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
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)Thierry Gayet
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversingEnrique López Mañas
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Test-Driven development; why you should never code without it
Test-Driven development; why you should never code without itTest-Driven development; why you should never code without it
Test-Driven development; why you should never code without itJad Salhani
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekPaco van Beckhoven
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 

Similar to 7 stages of unit testing (20)

7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
 
Google test training
Google test trainingGoogle test training
Google test training
 
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
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
Unit Testing in iOS
Unit Testing in iOSUnit Testing in iOS
Unit Testing in iOS
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
L08 Unit Testing
L08 Unit TestingL08 Unit Testing
L08 Unit Testing
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Unit testing on mobile apps
Unit testing on mobile appsUnit testing on mobile apps
Unit testing on mobile apps
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Test-Driven development; why you should never code without it
Test-Driven development; why you should never code without itTest-Driven development; why you should never code without it
Test-Driven development; why you should never code without it
 
TDD Agile Tour Beirut
TDD  Agile Tour BeirutTDD  Agile Tour Beirut
TDD Agile Tour Beirut
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech Week
 
Python testing
Python  testingPython  testing
Python testing
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 

More from Jorge Ortiz

Tell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature FlagsTell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature FlagsJorge Ortiz
 
Unit Test your Views
Unit Test your ViewsUnit Test your Views
Unit Test your ViewsJorge Ortiz
 
Control your Voice like a Bene Gesserit
Control your Voice like a Bene GesseritControl your Voice like a Bene Gesserit
Control your Voice like a Bene GesseritJorge Ortiz
 
Kata gilded rose en Golang
Kata gilded rose en GolangKata gilded rose en Golang
Kata gilded rose en GolangJorge Ortiz
 
CYA: Cover Your App
CYA: Cover Your AppCYA: Cover Your App
CYA: Cover Your AppJorge Ortiz
 
Refactor your way forward
Refactor your way forwardRefactor your way forward
Refactor your way forwardJorge Ortiz
 
201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SG201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SGJorge Ortiz
 
Home Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinHome Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinJorge Ortiz
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowersJorge Ortiz
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive AppsJorge Ortiz
 
iOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editioniOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editionJorge Ortiz
 
Android clean architecture workshop 3h edition
Android clean architecture workshop 3h editionAndroid clean architecture workshop 3h edition
Android clean architecture workshop 3h editionJorge Ortiz
 
To Protect & To Serve
To Protect & To ServeTo Protect & To Serve
To Protect & To ServeJorge Ortiz
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshopJorge Ortiz
 
Escape from Mars
Escape from MarsEscape from Mars
Escape from MarsJorge Ortiz
 
Why the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID ArchitectureWhy the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID ArchitectureJorge Ortiz
 
Dependence day insurgence
Dependence day insurgenceDependence day insurgence
Dependence day insurgenceJorge Ortiz
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowersJorge Ortiz
 
TDD for the masses
TDD for the massesTDD for the masses
TDD for the massesJorge Ortiz
 
Building for perfection
Building for perfectionBuilding for perfection
Building for perfectionJorge Ortiz
 

More from Jorge Ortiz (20)

Tell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature FlagsTell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature Flags
 
Unit Test your Views
Unit Test your ViewsUnit Test your Views
Unit Test your Views
 
Control your Voice like a Bene Gesserit
Control your Voice like a Bene GesseritControl your Voice like a Bene Gesserit
Control your Voice like a Bene Gesserit
 
Kata gilded rose en Golang
Kata gilded rose en GolangKata gilded rose en Golang
Kata gilded rose en Golang
 
CYA: Cover Your App
CYA: Cover Your AppCYA: Cover Your App
CYA: Cover Your App
 
Refactor your way forward
Refactor your way forwardRefactor your way forward
Refactor your way forward
 
201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SG201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SG
 
Home Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinHome Improvement: Architecture & Kotlin
Home Improvement: Architecture & Kotlin
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowers
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
 
iOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editioniOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h edition
 
Android clean architecture workshop 3h edition
Android clean architecture workshop 3h editionAndroid clean architecture workshop 3h edition
Android clean architecture workshop 3h edition
 
To Protect & To Serve
To Protect & To ServeTo Protect & To Serve
To Protect & To Serve
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshop
 
Escape from Mars
Escape from MarsEscape from Mars
Escape from Mars
 
Why the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID ArchitectureWhy the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID Architecture
 
Dependence day insurgence
Dependence day insurgenceDependence day insurgence
Dependence day insurgence
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowers
 
TDD for the masses
TDD for the massesTDD for the masses
TDD for the masses
 
Building for perfection
Building for perfectionBuilding for perfection
Building for perfection
 

Recently uploaded

Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxEasyPrinterHelp
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsUXDXConf
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
Buy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfBuy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfEasyPrinterHelp
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyUXDXConf
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastUXDXConf
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 

Recently uploaded (20)

Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptx
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Buy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfBuy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdf
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 

7 stages of unit testing

  • 1. 7 Stages of Unit Testing in Android Jorge D. Ortiz Fuentes @jdortiz #7SUnitTest
  • 3. #7SUnitTest Daring as a fool ★ Speaking from the shoulders of giants. Look up here! ★ This is not UnitTesting 101, but complementary to it
  • 4. 1.
  • 6. But my code is always awesome!
  • 7. #7SUnitTest Unit Tests ★ Prove correctness of different aspects of the public interface. • Prove instead of intuition • Define contract and assumptions • Document the code • Easier refactoring or change ★ Reusable code = code + tests
  • 8. #7SUnitTest Use Unit Testing Incrementally ★ You don’t have to write every unit test ★ Start with the classes that take care of the logic • If mixed apply SOLID ★ The easier entry point are bugs
  • 9. 2.
  • 11. C’mon, it takes ages to write tests!
  • 12. Time writing tests < Time debugging
  • 13. #7SUnitTest Good & Bad News ★ Most things are already available in Android Studio ★ Projects are created with • test package • ApplicationTest class ★ It requires some tweaking ★ Google docs are for Eclipse • modules instead of projects • different UI…
  • 15. Run from IDE Run in (V)Device
  • 16. 3.
  • 17. Anger
  • 18. How do I write those f***ing tests?
  • 19. #7SUnitTest Types of Unit Tests ★ Test return value ★ Test state ★ Test behavior
  • 20. public class TaskTests extends TestCase { final static String TASK_NAME = "First task"; final static String TASK_DONE_STRING = "First task: Done"; final static String TASK_NOT_DONE_STRING = "First task: NOT done"; Task mTask; @Override public void setUp() throws Exception { super.setUp(); mTask = new Task(); } @Override public void tearDown() throws Exception { super.tearDown(); mTask = null; } public void testDoneStatusIsDisplayedProperly() throws Exception { mTask.setName(TASK_NAME); mTask.setDone(true); String taskString = mTask.toString(); assertEquals("String must be "taskname: Done"", TASK_DONE_STRING, taskString); } public void testNotDoneStatusIsDisplayedProperly() throws Exception { mTask.setName(TASK_NAME); mTask.setDone(false); assertEquals("String must be "taskname: NOT done "", TASK_NOT_DONE_STRING, mTask.toString()); } } Example public class Task { private String mName; private Boolean mDone; public String getName() { return mName; } public void setName(String name) { mName = name; } } public Boolean getDone() { return mDone; } public void setDone(Boolean done) { mDone = done; } @Override public String toString() { return mName + ": " + (mDone?"Done":"NOT done"); } }
  • 21. public class ModelAndLogicTestSuite extends TestSuite { public static Test suite() { return new TestSuiteBuilder(ModelAndLogicTestS uite.class) .includePackages(“c om.powwau.app.interactor”, “com.powwau.app.data”) .build(); } public ModelAndLogicTestSuite() { super(); } } Running more than one TestCase public class FullTestSuite extends TestSuite { public static Test suite() { return new TestSuiteBuilder(FullTestSuite.cl ass) .includeAllPackag esUnderHere() .build(); } public FullTestSuite() { super(); } }
  • 22. Instrumentation Tests public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> { Activity mActivity; public MainActivityUnitTest() { super(MainActivity.class); } @Override public void setUp() throws Exception { super.setUp(); mActivity = getActivity(); } public void testHelloIsDisplayed() throws Exception { onView(withText(“Hello world!")).check(ViewAssertions.matches(isDisplayed())); } public void testSalutationChangesWithButtonClick() throws Exception { onView(withText("Touch Me")).perform(click()); onView(withText("Bye bye, Moon!”)).check(ViewAssertions.matches(isDisplayed())); } }
  • 23. 4.
  • 25. Ok, I’ll write some tests, but make my life simpler
  • 26. #7SUnitTest Dependency Injection ★ Control behavior of the dependencies • Constructor • Method overwriting • Property injection:Lazy instantiation ★ Or use a DI framework: Dagger 2
  • 27. Dependency Injection for Poor Developers public void preserveUserName(String name) { SharedPreferences prefs = getPreferences(“appPrefs”, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString(USER_NAME_KEY, name); editor.commit(); }
  • 28. Dependency Injection for Poor Developers public void preserveUserName(String name) { SharedPreferences prefs = getAppPrefs(); SharedPreferences.Editor editor = prefs.edit(); editor.putString(USER_NAME_KEY, name); editor.commit(); } SharedPreferences getAppPrefs() { if (mAppPrefs == null) { mAppPrefs = getPreferences(“appPrefs”, Context.MODE_PRIVATE); } return mAppPrefs; }
  • 29. DataRepo dataRepoMock = mock(DataRepo.class); when(dataRepoMock.existsObjWithId(23)).thenReturn( true); verify(dataRepoMock).deleteObjWithId(23); Simulating and Testing Behavior ★ Stubs & Mocks • Both are fake objects • Stubs provide desired responses to the SUT • Mocks also expect certain behaviors
  • 30. 5.
  • 31. Guilt
  • 33. #7SUnitTest Problems so far ★ Tests run in (v)device: slow ★ Unreliable behavior: • Command line • Integration with mocking
  • 34. 6.
  • 36. My tests are never good enough!
  • 37. #7SUnitTest Use JUnit 4 ★ Don’t extend TestCase ★ Don’t start with test (@Test instead) ★ @Before & @After instead of setUp and tearDown. Also for the class ★ @ignore ★ Exceptions & timeouts (@Test params) ★ @Theory & @DataPoints
  • 38. Gradle config sourceSets { test.setRoot(“src/test”) } dependencies { testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:1.9.5' androidTestCompile 'junit:junit:4.12' androidTestCompile 'org.mockito:mockito- core:1.9.5' }
  • 39. How to Use JUnit 4
  • 40. #7SUnitTest CLI-aware Also ★ ./gradlew check • lint • test ★ Open app/build/reports/tests/debug/ index.html
  • 41. 7.
  • 44. #7SUnitTest Evolve ★ Clean Architecture ★ TDD ★ Functional tests :monkeyrunner ★ CI (Jenkins)