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 Testing
Trinity 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
 
Software testing
Software testingSoftware testing
Software testing
Madhumita Chatterjee
 
Types of software testing
Types of software testingTypes of software testing
Types of software testing
Testbytes
 
Testing methodology
Testing methodologyTesting methodology
Testing methodology
Dina Hanbazazah
 
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
KostCare
 
Transactionflow
TransactionflowTransactionflow
Transactionflow
vamshi batchu
 
software testing methodologies
software testing methodologiessoftware testing methodologies
software testing methodologies
Jhonny Jhon
 
Software Testing
Software TestingSoftware Testing
Software Testing
Kiran Kumar
 
Types of Software Testing
Types of Software TestingTypes of Software Testing
Types of Software TestingNishant Worah
 
Testing fundamentals
Testing fundamentalsTesting fundamentals
Testing fundamentals
Raviteja Chowdary Adusumalli
 
System testing
System testingSystem testing
System testing
Abdullah-Al- Mahmud
 
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, Pune
sanjayjadhav8789
 
Software testing methods
Software testing methodsSoftware testing methods
Software testing methods
Homa Pourmohammadi
 
Software Testing or Quality Assurance
Software Testing or Quality AssuranceSoftware Testing or Quality Assurance
Software Testing or Quality Assurance
Trimantra Software Solutions
 
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
 
Types of testing
Types of testingTypes of testing
Types of testing
Valarmathi Srinivasan
 
System testing
System testingSystem testing
System testing
Bernie Fishpool
 

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 iOS
Jorge Ortiz
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
Godfrey Nolan
 
Google test training
Google test trainingGoogle test training
Google test training
Thierry 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 Test
Seb 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
 
L08 Unit Testing
L08 Unit TestingL08 Unit Testing
L08 Unit Testing
Ólafur Andri Ragnarsson
 
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
Buşra Deniz, CSM
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversing
Enrique López Mañas
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
guestc8093a6
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
Peter Arato
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
Steven 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 it
Jad Salhani
 
TDD Agile Tour Beirut
TDD  Agile Tour BeirutTDD  Agile Tour Beirut
TDD Agile Tour Beirut
Agile Tour Beirut
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
Roman Okolovich
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech Week
Paco 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 Flags
Jorge Ortiz
 
Unit Test your Views
Unit Test your ViewsUnit Test your Views
Unit Test your Views
Jorge 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 Gesserit
Jorge Ortiz
 
Kata gilded rose en Golang
Kata gilded rose en GolangKata gilded rose en Golang
Kata gilded rose en Golang
Jorge Ortiz
 
CYA: Cover Your App
CYA: Cover Your AppCYA: Cover Your App
CYA: Cover Your App
Jorge Ortiz
 
Refactor your way forward
Refactor your way forwardRefactor your way forward
Refactor your way forward
Jorge 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 SG
Jorge Ortiz
 
Home Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinHome Improvement: Architecture & Kotlin
Home Improvement: Architecture & Kotlin
Jorge Ortiz
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowers
Jorge Ortiz
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
Jorge Ortiz
 
iOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editioniOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h edition
Jorge Ortiz
 
Android clean architecture workshop 3h edition
Android clean architecture workshop 3h editionAndroid clean architecture workshop 3h edition
Android clean architecture workshop 3h edition
Jorge Ortiz
 
To Protect & To Serve
To Protect & To ServeTo Protect & To Serve
To Protect & To Serve
Jorge Ortiz
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshop
Jorge Ortiz
 
Escape from Mars
Escape from MarsEscape from Mars
Escape from Mars
Jorge 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 Architecture
Jorge Ortiz
 
Dependence day insurgence
Dependence day insurgenceDependence day insurgence
Dependence day insurgence
Jorge Ortiz
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowers
Jorge Ortiz
 
TDD for the masses
TDD for the massesTDD for the masses
TDD for the masses
Jorge Ortiz
 
Building for perfection
Building for perfectionBuilding for perfection
Building for perfection
Jorge 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

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 

Recently uploaded (20)

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 

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)