SlideShare una empresa de Scribd logo
1 de 18
Descargar para leer sin conexión


Unit Testing 

on 

Android
Buşra Deniz
@busradeniz
Droidcon Berlin 2015
ABOUT ME
busradeniz
busradeniz89@gmail.com
busradeniz.com
Certified Scrum Master & Mobile Software Developer @Netaş 

Co-Organizer @
Co-Organizer @
Master Student in SWE @Bogazici University
Co-Author of “Android Mutfağından Seçmeler”
AGENDA
01
02
03
04
What is unit test ?
Why test your code ?
Test Frameworks for Android
QA
UNIT TEST
Testing single unit of code
WHY TEST YOUR CODE ?
UN
Useful 

document

Reduce
testing
time
Bug fix
early
Refine 

Design
Unit
Test
Unit testing finds problems
early in the development cycle.
This includes both bugs in the
programmer's implementation
and flaws or missing parts of
the specification for the unit.
Unit testing provides a sort of living
documentation of the system.
Developers looking to learn what
functionality is provided by a unit,
and how to use it, can look at the
unit tests to gain a basic
understanding of the unit's interface
UT always forces you software parts
that can tests easily. While you are
writing unit tests for existing code,
you will realize that it is not too easy.
Your code should be proper in order
to isolate out parts of your SUT. By
this way, you need to refactor and
refine your code so as to write
successful unit tests.
Unit test covers the basic cases
of your software so the next
cycle of software testing can
include more complex scenarios.
For example, checking null
parameters can be handled in
unit tests so in the next cycle,
Test frameworks for Android
JUnit is a simple framework to write repeatable tests.
Asserts
Specify the expected output and compare
it with the output received
Test suites
Unit test cases are organized into test
suites for better management
Rules
Extend the functionality of JUnit by adding
behaviors to tests
Exception testing
Tests and verifies whether an exception
was thrown
Test setup and teardown
Sets up test data and tears down that data
or context, before and after running the
test
androidTestCompile ‘junit:junit:4.12’
Integration with build systems
Integrates the most popular build systems
for Java, including ANT, Maven, Gradle
Initial Test Case With Annotations
public class JUnitTestExamples {
@Before
public void setUp() {
//sets up test data, runs before test case
}

@Test
public void testAssertEquals() {
// test method
}

@After
public void tearDown() {
//tears down test data, runs after test case
}
}
JUnit annotations
@Test
@Before

@After

@BeforeClass

@AfterClass

@Ignore
Assertions
public class AssertTests {
@Test
public void testAssertArrayEquals() {
byte[] expected = "trial".getBytes();
byte[] actual = "trial".getBytes();
org.junit.Assert.assertArrayEquals("failure - byte arrays not same", expected, actual);
}
@Test
public void testAssertEquals() {
org.junit.Assert.assertEquals("failure - strings are not equal", "text", "text");
}
@Test
public void testAssertFalse() {
org.junit.Assert.assertFalse("failure - should be false", true);
}
@Test
public void testAssertNotNull() {
org.junit.Assert.assertNotNull("should not be null", new Object());
}
}
JUnit provides
overloaded assertion
methods for all
primitive types and
Objects and arrays
(of primitives or
Objects).
Test Suites
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestFeatureLogin.class,
TestFeatureLogout.class,
TestFeatureNavigate.class,
TestFeatureUpdate.class
})
public class FeatureTestSuite {
// the class remains empty,
// used only as a holder for the above annotations
}
Using “Suite” as a
runner allows you to
manually build a
suite containing tests
from many classes.
Mockito is a mocking framework that tastes really good. It lets you
write beautiful tests with clean & simple API.
mock() / @Mock
creates mock
optionally specify how it should behave via
Answer/ReturnValues/MockSettings
when()/given() to specify how a mock
should behave
spy() / @Spy
partial mocking, real methods are invoked
but still can be verified and stubbed
verify()
checks methods were called with given
arguments
@InjectMocks
automatically inject mocks/spies fields
annotated with @Spy or @Mock
androidTestCompile ‘org.mockito:mockito-core:1.9.5’
import static org.mockito.Mockito.*;
//mock creation
List mockedList = mock(List.class);
//using mock object
mockedList.add("one");
mockedList.clear();
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
Once created, mock will remember all interactions.Then you can selectively verify whatever
interaction you are interested in.
mock()
public class ArticleManagerTest {
@Mock private ArticleCalculator calculator;
@Mock private ArticleDatabase database;
@Mock private UserProvider userProvider;
private ArticleManager manager;
@Before public void setup() {
MockitoAnnotations.initMocks(this);
}
}
@Mock
List list = new LinkedList();
List spy = spy(list);
//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);
//using the spy calls real methods
spy.add("one");
spy.add("two");
//prints "one" - the first element of a list
System.out.println(spy.get(0));
//size() method was stubbed - 100 is printed
System.out.println(spy.size());
//optionally, you can verify
verify(spy).add("one");
verify(spy).add("two");
spy() @Spy
@Spy Foo spyOnFoo = new Foo();
//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);
//using the spy calls real methods
spy.add("one");
spy.add("two");
//prints "one" - the first element of a list
System.out.println(spy.get(0));
//size() method was stubbed - 100 is printed
System.out.println(spy.size());
//optionally, you can verify
verify(spy).add("one");
verify(spy).add("two");


Running tests is too slow because JUnit tests need an Android
emulator or device
java.lang.RuntimeException: Stub!
Robolectric lets you run your tests on your workstation, or on your
Continuous Integration environment in a regular JVM, without an
emulator.
@RunWith(RobolectricTestRunner.class)
public class WelcomeActivityTest {
@Test
public void clickingLogin_shouldStartLoginActivity() {
WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
activity.findViewById(R.id.login).performClick();
Intent expectedIntent = new Intent(activity, WelcomeActivity.class);
assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent);
}
}
Robolectric supports
resource handling,
e.g., inflation of
views. You can also
use the
findViewById() to
search in a view.
androidTestCompile ‘org:robolectric:robolectric:2.4’
Test Coverage
JaCoCo is a free code coverage library for Java
it supports instruction, branch, line, method and class coverage
Test Coverage
The green lines represent
parts of the code which were
fully covered by tests. 



The yellow line means that
given branch was not fully
covered because its
condition never evaluated to
true.
The red line was never
executed by our tests.
Thanks
Buşra Deniz
@busradeniz
Droidcon Berlin 2015

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Unit testing
Unit testingUnit testing
Unit testing
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
TestNG
TestNGTestNG
TestNG
 
Unit testing
Unit testingUnit testing
Unit testing
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
 
testng
testngtestng
testng
 
SWTBot Tutorial
SWTBot TutorialSWTBot Tutorial
SWTBot Tutorial
 
SwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made EasySwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made Easy
 
Android testing
Android testingAndroid testing
Android testing
 
3 j unit
3 j unit3 j unit
3 j unit
 
Introduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit frameworkIntroduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit framework
 

Destacado (16)

Company Profile - Compressed
Company Profile - CompressedCompany Profile - Compressed
Company Profile - Compressed
 
Mech nacp lab
Mech nacp labMech nacp lab
Mech nacp lab
 
Lab manual asp.net
Lab manual asp.netLab manual asp.net
Lab manual asp.net
 
Teks ekposisi
Teks ekposisiTeks ekposisi
Teks ekposisi
 
Cn lab manual
Cn lab manualCn lab manual
Cn lab manual
 
Computer applications in civil engineering lab
Computer applications in civil engineering labComputer applications in civil engineering lab
Computer applications in civil engineering lab
 
Computer hardware and simulation lab manual
Computer  hardware and simulation lab manualComputer  hardware and simulation lab manual
Computer hardware and simulation lab manual
 
Oops lab manual
Oops lab manualOops lab manual
Oops lab manual
 
Softwareenggineering lab manual
Softwareenggineering lab manualSoftwareenggineering lab manual
Softwareenggineering lab manual
 
Java final lab
Java final labJava final lab
Java final lab
 
Graphics User Interface Lab Manual
Graphics User Interface Lab ManualGraphics User Interface Lab Manual
Graphics User Interface Lab Manual
 
Network security Lab manual
Network security Lab manual Network security Lab manual
Network security Lab manual
 
Eurest Breakfast White Paper
Eurest Breakfast White PaperEurest Breakfast White Paper
Eurest Breakfast White Paper
 
WebRTC on Mobile
WebRTC on MobileWebRTC on Mobile
WebRTC on Mobile
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 

Similar a Unit Testing on Android - Droidcon Berlin 2015

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptdavejohnson
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightOpenDaylight
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworksTomáš Kypta
 
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
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in JavaAnkur Maheshwari
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversingEnrique López Mañas
 
Comparative Development Methodologies
Comparative Development MethodologiesComparative Development Methodologies
Comparative Development Methodologieselliando dias
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactusHimanshu
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 

Similar a Unit Testing on Android - Droidcon Berlin 2015 (20)

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
J Unit
J UnitJ Unit
J Unit
 
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
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversing
 
Comparative Development Methodologies
Comparative Development MethodologiesComparative Development Methodologies
Comparative Development Methodologies
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 

Último

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 

Último (20)

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 

Unit Testing on Android - Droidcon Berlin 2015

  • 1. 
 Unit Testing 
 on 
 Android Buşra Deniz @busradeniz Droidcon Berlin 2015
  • 2. ABOUT ME busradeniz busradeniz89@gmail.com busradeniz.com Certified Scrum Master & Mobile Software Developer @Netaş 
 Co-Organizer @ Co-Organizer @ Master Student in SWE @Bogazici University Co-Author of “Android Mutfağından Seçmeler”
  • 3. AGENDA 01 02 03 04 What is unit test ? Why test your code ? Test Frameworks for Android QA
  • 5. WHY TEST YOUR CODE ? UN Useful 
 document
 Reduce testing time Bug fix early Refine 
 Design Unit Test Unit testing finds problems early in the development cycle. This includes both bugs in the programmer's implementation and flaws or missing parts of the specification for the unit. Unit testing provides a sort of living documentation of the system. Developers looking to learn what functionality is provided by a unit, and how to use it, can look at the unit tests to gain a basic understanding of the unit's interface UT always forces you software parts that can tests easily. While you are writing unit tests for existing code, you will realize that it is not too easy. Your code should be proper in order to isolate out parts of your SUT. By this way, you need to refactor and refine your code so as to write successful unit tests. Unit test covers the basic cases of your software so the next cycle of software testing can include more complex scenarios. For example, checking null parameters can be handled in unit tests so in the next cycle,
  • 7. JUnit is a simple framework to write repeatable tests. Asserts Specify the expected output and compare it with the output received Test suites Unit test cases are organized into test suites for better management Rules Extend the functionality of JUnit by adding behaviors to tests Exception testing Tests and verifies whether an exception was thrown Test setup and teardown Sets up test data and tears down that data or context, before and after running the test androidTestCompile ‘junit:junit:4.12’ Integration with build systems Integrates the most popular build systems for Java, including ANT, Maven, Gradle
  • 8. Initial Test Case With Annotations public class JUnitTestExamples { @Before public void setUp() { //sets up test data, runs before test case }
 @Test public void testAssertEquals() { // test method }
 @After public void tearDown() { //tears down test data, runs after test case } } JUnit annotations @Test @Before
 @After
 @BeforeClass
 @AfterClass
 @Ignore
  • 9. Assertions public class AssertTests { @Test public void testAssertArrayEquals() { byte[] expected = "trial".getBytes(); byte[] actual = "trial".getBytes(); org.junit.Assert.assertArrayEquals("failure - byte arrays not same", expected, actual); } @Test public void testAssertEquals() { org.junit.Assert.assertEquals("failure - strings are not equal", "text", "text"); } @Test public void testAssertFalse() { org.junit.Assert.assertFalse("failure - should be false", true); } @Test public void testAssertNotNull() { org.junit.Assert.assertNotNull("should not be null", new Object()); } } JUnit provides overloaded assertion methods for all primitive types and Objects and arrays (of primitives or Objects).
  • 10. Test Suites import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestFeatureLogin.class, TestFeatureLogout.class, TestFeatureNavigate.class, TestFeatureUpdate.class }) public class FeatureTestSuite { // the class remains empty, // used only as a holder for the above annotations } Using “Suite” as a runner allows you to manually build a suite containing tests from many classes.
  • 11. Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. mock() / @Mock creates mock optionally specify how it should behave via Answer/ReturnValues/MockSettings when()/given() to specify how a mock should behave spy() / @Spy partial mocking, real methods are invoked but still can be verified and stubbed verify() checks methods were called with given arguments @InjectMocks automatically inject mocks/spies fields annotated with @Spy or @Mock androidTestCompile ‘org.mockito:mockito-core:1.9.5’
  • 12. import static org.mockito.Mockito.*; //mock creation List mockedList = mock(List.class); //using mock object mockedList.add("one"); mockedList.clear(); //verification verify(mockedList).add("one"); verify(mockedList).clear(); Once created, mock will remember all interactions.Then you can selectively verify whatever interaction you are interested in. mock() public class ArticleManagerTest { @Mock private ArticleCalculator calculator; @Mock private ArticleDatabase database; @Mock private UserProvider userProvider; private ArticleManager manager; @Before public void setup() { MockitoAnnotations.initMocks(this); } } @Mock
  • 13. List list = new LinkedList(); List spy = spy(list); //optionally, you can stub out some methods: when(spy.size()).thenReturn(100); //using the spy calls real methods spy.add("one"); spy.add("two"); //prints "one" - the first element of a list System.out.println(spy.get(0)); //size() method was stubbed - 100 is printed System.out.println(spy.size()); //optionally, you can verify verify(spy).add("one"); verify(spy).add("two"); spy() @Spy @Spy Foo spyOnFoo = new Foo(); //optionally, you can stub out some methods: when(spy.size()).thenReturn(100); //using the spy calls real methods spy.add("one"); spy.add("two"); //prints "one" - the first element of a list System.out.println(spy.get(0)); //size() method was stubbed - 100 is printed System.out.println(spy.size()); //optionally, you can verify verify(spy).add("one"); verify(spy).add("two");
  • 14. 
 Running tests is too slow because JUnit tests need an Android emulator or device java.lang.RuntimeException: Stub! Robolectric lets you run your tests on your workstation, or on your Continuous Integration environment in a regular JVM, without an emulator.
  • 15. @RunWith(RobolectricTestRunner.class) public class WelcomeActivityTest { @Test public void clickingLogin_shouldStartLoginActivity() { WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class); activity.findViewById(R.id.login).performClick(); Intent expectedIntent = new Intent(activity, WelcomeActivity.class); assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent); } } Robolectric supports resource handling, e.g., inflation of views. You can also use the findViewById() to search in a view. androidTestCompile ‘org:robolectric:robolectric:2.4’
  • 16. Test Coverage JaCoCo is a free code coverage library for Java it supports instruction, branch, line, method and class coverage
  • 17. Test Coverage The green lines represent parts of the code which were fully covered by tests. 
 
 The yellow line means that given branch was not fully covered because its condition never evaluated to true. The red line was never executed by our tests.