SlideShare a Scribd company logo
1 of 35
l

Test-Driven Development and
Android

•
•

Except as otherwise noted, the content of this presentation is
licensed under the Creative Commons Attribution 2.5 License.
l

l

l
l
l
l

TDD in Android

Android SDK integrates JUnit 3
l 1.6 does not support JUnit 4
Many helper TestCase classes
Recommended best practice to put
tests in separate project but share
folder
l Eclipse “New Android Project”
l wizard will do this for you

– Beware if both src and test projects use same libraries

– (see http://jimshowalter.blogspot.com/2009/10/developing-android-with-multiple.html)
l

Android TestCase Classes
l

l

l

l

Android TestCase Classes

Basic JUnit tests
l TestCase (run tests with assert methods)
When you need an Activity Context
l AndroidTestCase (see getContext())
When you want to use a Mock Context
l ApplicationTestCase (call setContext() before calling
createApplication() which calls onCreate())
l

l

l

Android TestCase Classes

When you want to test just one Activity
l ActivityUnitTestCase (allows you to ask if the Activity
has started another Activity or called finish() or requested
a particular orientation)
When you want to do a functional test on an Activity
l ActivityInstrumentationTestCase2 (allows you to send
key events to your Activity)
l

l

l

l

Android TestCase Classes

When you want to test a Content Provider
l ProviderTestCase2
When you want to test a Service
l ServiceTestCase
When you want to stress test the UI
l Monkey
l http://d.android.com/guide/developing/tools/monkey.html
l
l

Android TestCase How-to

Add instrumentation to ApplicationManifest.xml
• <?xml version="1.0" encoding="utf-8"?>
• <manifest xmlns:android="http://schemas.android.com/apk/res/android"
•
package=“com.simexusa.testcaseexamples" android:versionCode="1"
•
android:versionName="1.0">
•
<application android:icon="@drawable/icon" android:label="@string/app_name"
•
android:debuggable="true">
•
<uses-library android:name="android.test.runner" />
•
<activity android:name=“SomeActivity android:label="@string/app_name">
•
<intent-filter>
•
<action android:name="android.intent.action.MAIN" />
•
<category android:name="android.intent.category.LAUNCHER" />
•
</intent-filter>
•
</activity>
•
</application>
•
<uses-sdk android:minSdkVersion="3" />
•
<instrumentation android:name="android.test.InstrumentationTestRunner"
•
android:targetPackage=“com.simexusa.testcaseexamples"
•
android:label="Tests for my example."/>
• </manifest>
l
l

Android TestCase How-to

Add instrumentation to ApplicationManifest.xml
l When creating a second project

• <?xml version="1.0" encoding="utf-8"?>
• <manifest xmlns:android="http://schemas.android.com/apk/res/android"
•
package="com.simexusa.testcaseexamples.test"
•
android:versionCode="1"
•
android:versionName="1.0">
•
<application android:icon="@drawable/icon" android:label="@string/app_name">
•
<uses-library android:name="android.test.runner" />
•
</application>
•
<uses-sdk android:minSdkVersion="4" />
•
<instrumentation android:targetPackage="com.simexusa.testcaseexamples"
•
android:name="android.test.InstrumentationTestRunner" />
• </manifest>
l

Create a new JUnit Test Case
l

Create a new JUnit Test Case
l
l

Testing POJO’s

Plain Old Java Objects
l (i.e. independent of frameworks like Android or J2EE)
• import junit.framework.TestCase;
• import edu.calpoly.android.lab4.Joke;
• public class JokeTest extends TestCase {
• public void testJoke() {
•
Joke joke = new Joke();
•
assertTrue("m_strJoke should be initialized to "".", joke.getJoke().equals(""));
•
assertTrue("m_strAuthorName should be initialized to "".",
•
joke.getAuthor().equals(""));
•
assertEquals("m_nRating should be initialized to Joke.UNRATED.",
•
Joke.UNRATED, joke.getRating());
• }
• }
l

Create a new JUnit Test Case
l

Run the tests
l
l

JUnit 3 How-to

Import the JUnit framework

• import junit.framework.*;
Create a subclass of TestCase
• public class TestBank extends TestCase {
l
Write methods in the form testXXX()
l
Use assertXXX() methods
•
•
•
•
l

public void testCreateBank() {
Bank b = new Bank();
assertNotNull(b);
}
Compile test and functional code; Run a TestRunner to
execute tests; Keep the bar green!
l
l

Fixtures

Notice redundancy in test methods

• import junit.framework.TestCase;
• public class TestBank extends TestCase {
•
public void testCreateBank() {
•
Bank b = new Bank();
•
assertNotNull(b);
•
}
•
public void testCreateBankEmpty() {
•
Bank b = new Bank();
•
assertEquals(b.getNumAccounts(),0);
•
}
• }

l

Common test setup can be placed in a method
named setUp() which is run before each test
l
l

tearDown()

tearDown() is run after each test
l Used for cleaning up resources such as files, network, or
database connections

• import junit.framework.TestCase;
• public class TestBank extends TestCase {
•
private Bank b;
•
public void setUp() {
•
b = new Bank();
•
}
•
public void tearDown() {
•
b = null;
• tearDown()
•
}
•
…
• }

is run after each test
l

setUp()

• import junit.framework.*;
• public class TestBank extends TestCase {
•
private Bank b;
•
public void setUp() {
• setUp() is run
•
b = new Bank();
•
}
•
public void testCreateBank() {
•
assertNotNull(b);
•
}
•
public void testCreateBankEmpty() {
•
assertEquals(b.getNumAccounts(),0);
•
}
•
public void testAddAccount() {
•
Account a = new Account("John Doe",123456,0.0);
•
b.addAccount(a);
•
assertEquals(b.getNumAccounts(),1);
•
}
• }

before each test
l
l

Grouping Tests with @xTest

Some tests run fast, others don’t
l You can separate them with @SmallTest, @MediumTest,
@LargeTest

• public class JokeTest extends TestCase {
•
•
•
•
•
•
•
•
•
•
•
•

@SmallTest
/**
* Test Default Constructor
*/
public void testJoke() {
Joke joke = new Joke();
assertTrue("m_strJoke should be initialized to "".", joke.getJoke().equals(""));
assertTrue("m_strAuthorName should be initialized to "".",
joke.getAuthor().equals(""));
assertEquals("m_nRating should be initialized to Joke.UNRATED.",
Joke.UNRATED, joke.getRating());
}
l

l

Running Tests with @xTest

Run the tests with adb from the command line
l http://developer.android.com/reference/android/test/Instrumenta
tionTestRunner.html

• C:adb shell am instrument -w -e size
small edu.calpoly.android.lab4/android.test.InstrumentationTestRunner
•
•
•
•

edu.calpoly.android.lab4.tests.dflt.JokeCursorAdapterTest:....
edu.calpoly.android.lab4.tests.dflt.JokeTest:.........
Test results for InstrumentationTestRunner=.............
Time: 1.975

• OK (13 tests)
l

•
•
•
•
•
•
•
•
•
•
•
•
•
•

Testing Campus Maps

package com.simexusa.campusmaps_full;
import com.simexusa.campusmaps_full.CampusMap;
import com.simexusa.campusmaps_full.TranslatorUtility;
import junit.framework.TestCase;
public class TestTranslatorUtility extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
public void testTranslateLatToY() {
double b1lat = 35.302518;
double b2lat = 35.299365;
int b1py = 445;
int b2py = 840;
double latitude = 35.299812;
assertEquals(784,TranslatorUtility.latToCoordinate(latitude,b1lat,b2lat,b1py,b2py));
• }
l

•
•
•
•
•

Testing Campus Maps

package com.simexusa.campusmaps_full;
import com.simexusa.campusmaps_full.CampusMap;
import com.simexusa.campusmaps_full.TranslatorUtility;
import junit.framework.TestCase;
public class TestTranslatorUtility extends TestCase {

• protected void setUp() throws Exception {
•
super.setUp();
• }
• public void testTranslateLatToY() {
•
double b1lat = 35.302518;
•
double b2lat = 35.299365;
•
int b1py = 445;
•
int b2py = 840;
• Test complicated methods
•
double latitude = 35.299812;
•
assertEquals(784,TranslatorUtility.latToCoordinate(latitude,b1lat,b2lat,b1py,b2py));
• }
l

Testing Campus Maps

• public void testSplit2() {
• String s = "go+180";
• String [] results = s.split("+");
• assertEquals(results[0],"go");
• assertEquals(results[1],"180");
• }

• Explore library API’s

• Verify it works like I expect
• public void testParser() {
• CampusMap [] maps = TranslatorUtility.parseMapData(
•
"Bethel College|http://www.bethelks.edu/map/bcmap.png|” +
•
“39.298664|39.296903|-76.593761|-76.590527|383|614|171|352n");
• assertEquals(maps[0].title,"Bethel College");
• }
• Functional tests
• This one gets data from the web
• public void testGetMaps() {
• CampusMap[] myCampusMaps = new CampusMap[5];
• TranslatorUtility.retrieveMapData("http://simexusa.com/cm/fav5defaultmapdata.txt",
•
myCampusMaps);
• assertEquals(myCampusMaps[0].title,"Cal Poly - SLO");
• }
l

TDD in Software Development Lifecycle
l

l

What is Test-Driven Development?

TDD is a design (and testing) approach involving short,
rapid iterations of
l

Unit Test

l

Code

l

Refactor
l

l

l

What is Refactoring?

Changing the structure of the code without changing its
behavior
l Example refactorings:
l Rename
l Extract method/extract interface
l Inline
l Pull up/Push down
Some IDE’s (e.g. Eclipse) include automated refactorings
l

Test-Driven Development

l

Short introduction1
l Test-driven development (TDD) is the craft of producing automated tests for
production code, and using that process to drive design and programming. For every
tiny bit of functionality in the production code, you first develop a test that specifies
and validates what the code will do. You then produce exactly as much code as will
enable that test to pass. Then you refactor (simplify and clarify) both the production
code and the test code.

•

1.
http://www.agilealliance.org/programs/roadmaps/Roadmap/tdd/tdd_index.htm
l

l

Some Types of Testing

Unit Testing
l
l

l

l

Testing individual units (typically methods)
White/Clear-box testing performed by original programmer
Integration and Functional Testing
• and may help here
l Testing interactions of units and testing use cases

Regression Testing
l

l

Testing previously tested components after changes

Stress/Load/Performance Testing
l

l

• TDD focuses here

How many transactions/users/events/… can the system handle?

Acceptance Testing
l

• and here

Does the system do what the customer wants?
l

l
l

l

TDD Misconceptions

There are many misconceptions about TDD
They probably stem from the fact that the first word in
TDD is “Test”
TDD is not about testing,TDD is about design
l Automated tests are just a nice side effect
l

l

l

Functional Testing

ActivityInstrumentationTestCase2
l Allows us to create/start an Activity
l Get Views from the Activity (e.g. Buttons)
l Run things on the UI thread (e.g. click Buttons)
l Perform asserts in JUnit
Other options
l http://code.google.com/p/autoandroid/
l Formerly Positron
l Android + Selenium = Positron
• public class FunctionalTest extends
•
ActivityInstrumentationTestCase2<AdvancedJokeList> {
• public FunctionalTest() { super("edu.calpoly.android.lab2", AdvancedJokeList.class);}
• protected void setUp() throws Exception { super.setUp(); }
• public void testAddJoke() {
•
ArrayList<Joke> m_arrJokeList = null;
•
m_arrJokeList = this.retrieveHiddenMember("m_arrJokeList",
•
m_arrJokeList,getActivity());
•
assertEquals("Should be 3 default jokes",m_arrJokeList.size(),3);
•
getActivity().runOnUiThread(new Runnable() {
•
public void run() {
•
AdvancedJokeList theActivity = (AdvancedJokeList)getActivity();
•
EditText et = (EditText)theActivity.
•
findViewById(edu.calpoly.android.lab2.R.id.newJokeEditText);
•
Button bt = (Button)theActivity.
•
findViewById(edu.calpoly.android.lab2.R.id.addJokeButton);
•
et.setText("This is a test joke");
•
bt.performClick();
•
}});
•
getInstrumentation().waitForIdleSync(); // wait for the request to go through
•
assertEquals("Should be 4 jokes now",m_arrJokeList.size(),4);
•
assertEquals("Ensure the joke we added is really there",
•
m_arrJokeList.get(3).getJoke(),"This is a test joke");
• }
• @SuppressWarnings("unchecked")
• public <T> T retrieveHiddenMember(String memberName, T type, Object sourceObj) {
•
Field field = null;
•
T returnVal = null;
•
try {//Test for proper existence
•
field = sourceObj.getClass().getDeclaredField(memberName);
•
} catch (NoSuchFieldException e) {
•
fail("The field "" + memberName +
•
"" was renamed or removed. Do not rename or remove this member variable.");
•
}
•
field.setAccessible(true);
•
•
•
•
•
•

try {//Test for proper type
returnVal = (T)field.get(sourceObj);
} catch (ClassCastException exc) {
fail("The field "" + memberName +
"" had its type changed. Do not change the type on this member variable.");
}
•
•
•
•
•
•
•
•
•

// Boiler Plate Exception Checking. If any of these Exceptions are
// thrown it was because this method was called improperly.
catch (IllegalArgumentException e) {
fail ("This is an Error caused by the UnitTest!n Improper user of
retrieveHiddenMember(...) -- IllegalArgumentException:n Passed in the wrong object to
Field.get(...)");
} catch (IllegalAccessException e) {
fail ("This is an Error caused by the UnitTest!n Improper user of
retrieveHiddenMember(...) -- IllegalAccessException:n Field.setAccessible(true) should be
called.");
}
return returnVal;
}
l

l

Monkey

Random stress testing
l
l

l

l
l

From http://d.android.com/guide/developing/tools/monkey.html
When the Monkey runs, it generates events and sends them to the
system. It also watches the system under test and looks for three
conditions, which it treats specially:
If you have constrained the Monkey to run in one or more specific
packages, it watches for attempts to navigate to any other packages,
and blocks them.
If your application crashes or receives any sort of unhandled
exception, the Monkey will stop and report the error.
If your application generates an application not responding error, the
Monkey will stop and report the error.

• adb shell monkey -p edu.calpoly.lab2 -v 500
l

l

Android SDK documentation
l

l

http://developer.android.com/reference/junit/framework/T
estCase.html

Tutorial:
l

l

TDD and Android Resources

http://dtmilano.blogspot.com/2008/01/test-drivendevelopment-and-gui-testing.html

Blogs:
l
l

http://dtmilano.blogspot.com/search/label/test%20driven
%20development
http://jimshowalter.blogspot.com/2009/10/developingandroid-with-multiple.html

More Related Content

What's hot

Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Buşra Deniz, CSM
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversingEnrique López Mañas
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java ProjectVincent Massol
 
Iasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecampIasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecampCodecamp Romania
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic Peopledavismr
 
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustAndroid Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustInfinum
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsClare Macrae
 
Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Joachim Baumann
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
 
Unit testing and Android
Unit testing and AndroidUnit testing and Android
Unit testing and AndroidTomáš Kypta
 
Eclipse IDE, 2019.09, Java Development
Eclipse IDE, 2019.09, Java Development Eclipse IDE, 2019.09, Java Development
Eclipse IDE, 2019.09, Java Development Pei-Hsuan Hsieh
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 

What's hot (20)

Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversing
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java Project
 
Iasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecampIasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecamp
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
Test ng
Test ngTest ng
Test ng
 
TestNg_Overview_Config
TestNg_Overview_ConfigTestNg_Overview_Config
TestNg_Overview_Config
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic People
 
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustAndroid Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
 
Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
Unit testing and Android
Unit testing and AndroidUnit testing and Android
Unit testing and Android
 
L08 Unit Testing
L08 Unit TestingL08 Unit Testing
L08 Unit Testing
 
Eclipse IDE, 2019.09, Java Development
Eclipse IDE, 2019.09, Java Development Eclipse IDE, 2019.09, Java Development
Eclipse IDE, 2019.09, Java Development
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 

Similar to Tdd

Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Jimmy Lu
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projectsVincent Massol
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
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
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Jay Friendly
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETBen Hall
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)Rob Hale
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationRichard North
 
Testing and Building Android
Testing and Building AndroidTesting and Building Android
Testing and Building AndroidDroidcon Berlin
 
Level Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersLevel Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersVMware Tanzu
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF SummitOrtus Solutions, Corp
 
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
 

Similar to Tdd (20)

Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projects
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
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
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8
 
Junit
JunitJunit
Junit
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
Testing and Building Android
Testing and Building AndroidTesting and Building Android
Testing and Building Android
 
Level Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersLevel Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With Testcontainers
 
Agile Swift
Agile SwiftAgile Swift
Agile Swift
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
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)
 
Web works hol
Web works holWeb works hol
Web works hol
 

More from Training Guide

More from Training Guide (8)

Map
MapMap
Map
 
Persistences
PersistencesPersistences
Persistences
 
Theads services
Theads servicesTheads services
Theads services
 
App basic
App basicApp basic
App basic
 
Application lifecycle
Application lifecycleApplication lifecycle
Application lifecycle
 
Deployment
DeploymentDeployment
Deployment
 
Getting started
Getting startedGetting started
Getting started
 
Intents broadcastreceivers
Intents broadcastreceiversIntents broadcastreceivers
Intents broadcastreceivers
 

Recently uploaded

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

Tdd

  • 1. l Test-Driven Development and Android • • Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
  • 2. l l l l l l TDD in Android Android SDK integrates JUnit 3 l 1.6 does not support JUnit 4 Many helper TestCase classes Recommended best practice to put tests in separate project but share folder l Eclipse “New Android Project” l wizard will do this for you – Beware if both src and test projects use same libraries – (see http://jimshowalter.blogspot.com/2009/10/developing-android-with-multiple.html)
  • 4. l l l l Android TestCase Classes Basic JUnit tests l TestCase (run tests with assert methods) When you need an Activity Context l AndroidTestCase (see getContext()) When you want to use a Mock Context l ApplicationTestCase (call setContext() before calling createApplication() which calls onCreate())
  • 5. l l l Android TestCase Classes When you want to test just one Activity l ActivityUnitTestCase (allows you to ask if the Activity has started another Activity or called finish() or requested a particular orientation) When you want to do a functional test on an Activity l ActivityInstrumentationTestCase2 (allows you to send key events to your Activity)
  • 6. l l l l Android TestCase Classes When you want to test a Content Provider l ProviderTestCase2 When you want to test a Service l ServiceTestCase When you want to stress test the UI l Monkey l http://d.android.com/guide/developing/tools/monkey.html
  • 7. l l Android TestCase How-to Add instrumentation to ApplicationManifest.xml • <?xml version="1.0" encoding="utf-8"?> • <manifest xmlns:android="http://schemas.android.com/apk/res/android" • package=“com.simexusa.testcaseexamples" android:versionCode="1" • android:versionName="1.0"> • <application android:icon="@drawable/icon" android:label="@string/app_name" • android:debuggable="true"> • <uses-library android:name="android.test.runner" /> • <activity android:name=“SomeActivity android:label="@string/app_name"> • <intent-filter> • <action android:name="android.intent.action.MAIN" /> • <category android:name="android.intent.category.LAUNCHER" /> • </intent-filter> • </activity> • </application> • <uses-sdk android:minSdkVersion="3" /> • <instrumentation android:name="android.test.InstrumentationTestRunner" • android:targetPackage=“com.simexusa.testcaseexamples" • android:label="Tests for my example."/> • </manifest>
  • 8. l l Android TestCase How-to Add instrumentation to ApplicationManifest.xml l When creating a second project • <?xml version="1.0" encoding="utf-8"?> • <manifest xmlns:android="http://schemas.android.com/apk/res/android" • package="com.simexusa.testcaseexamples.test" • android:versionCode="1" • android:versionName="1.0"> • <application android:icon="@drawable/icon" android:label="@string/app_name"> • <uses-library android:name="android.test.runner" /> • </application> • <uses-sdk android:minSdkVersion="4" /> • <instrumentation android:targetPackage="com.simexusa.testcaseexamples" • android:name="android.test.InstrumentationTestRunner" /> • </manifest>
  • 9. l Create a new JUnit Test Case
  • 10. l Create a new JUnit Test Case
  • 11. l l Testing POJO’s Plain Old Java Objects l (i.e. independent of frameworks like Android or J2EE) • import junit.framework.TestCase; • import edu.calpoly.android.lab4.Joke; • public class JokeTest extends TestCase { • public void testJoke() { • Joke joke = new Joke(); • assertTrue("m_strJoke should be initialized to "".", joke.getJoke().equals("")); • assertTrue("m_strAuthorName should be initialized to "".", • joke.getAuthor().equals("")); • assertEquals("m_nRating should be initialized to Joke.UNRATED.", • Joke.UNRATED, joke.getRating()); • } • }
  • 12. l Create a new JUnit Test Case
  • 14.
  • 15. l l JUnit 3 How-to Import the JUnit framework • import junit.framework.*; Create a subclass of TestCase • public class TestBank extends TestCase { l Write methods in the form testXXX() l Use assertXXX() methods • • • • l public void testCreateBank() { Bank b = new Bank(); assertNotNull(b); } Compile test and functional code; Run a TestRunner to execute tests; Keep the bar green!
  • 16. l l Fixtures Notice redundancy in test methods • import junit.framework.TestCase; • public class TestBank extends TestCase { • public void testCreateBank() { • Bank b = new Bank(); • assertNotNull(b); • } • public void testCreateBankEmpty() { • Bank b = new Bank(); • assertEquals(b.getNumAccounts(),0); • } • } l Common test setup can be placed in a method named setUp() which is run before each test
  • 17. l l tearDown() tearDown() is run after each test l Used for cleaning up resources such as files, network, or database connections • import junit.framework.TestCase; • public class TestBank extends TestCase { • private Bank b; • public void setUp() { • b = new Bank(); • } • public void tearDown() { • b = null; • tearDown() • } • … • } is run after each test
  • 18. l setUp() • import junit.framework.*; • public class TestBank extends TestCase { • private Bank b; • public void setUp() { • setUp() is run • b = new Bank(); • } • public void testCreateBank() { • assertNotNull(b); • } • public void testCreateBankEmpty() { • assertEquals(b.getNumAccounts(),0); • } • public void testAddAccount() { • Account a = new Account("John Doe",123456,0.0); • b.addAccount(a); • assertEquals(b.getNumAccounts(),1); • } • } before each test
  • 19. l l Grouping Tests with @xTest Some tests run fast, others don’t l You can separate them with @SmallTest, @MediumTest, @LargeTest • public class JokeTest extends TestCase { • • • • • • • • • • • • @SmallTest /** * Test Default Constructor */ public void testJoke() { Joke joke = new Joke(); assertTrue("m_strJoke should be initialized to "".", joke.getJoke().equals("")); assertTrue("m_strAuthorName should be initialized to "".", joke.getAuthor().equals("")); assertEquals("m_nRating should be initialized to Joke.UNRATED.", Joke.UNRATED, joke.getRating()); }
  • 20. l l Running Tests with @xTest Run the tests with adb from the command line l http://developer.android.com/reference/android/test/Instrumenta tionTestRunner.html • C:adb shell am instrument -w -e size small edu.calpoly.android.lab4/android.test.InstrumentationTestRunner • • • • edu.calpoly.android.lab4.tests.dflt.JokeCursorAdapterTest:.... edu.calpoly.android.lab4.tests.dflt.JokeTest:......... Test results for InstrumentationTestRunner=............. Time: 1.975 • OK (13 tests)
  • 21. l • • • • • • • • • • • • • • Testing Campus Maps package com.simexusa.campusmaps_full; import com.simexusa.campusmaps_full.CampusMap; import com.simexusa.campusmaps_full.TranslatorUtility; import junit.framework.TestCase; public class TestTranslatorUtility extends TestCase { protected void setUp() throws Exception { super.setUp(); } public void testTranslateLatToY() { double b1lat = 35.302518; double b2lat = 35.299365; int b1py = 445; int b2py = 840; double latitude = 35.299812; assertEquals(784,TranslatorUtility.latToCoordinate(latitude,b1lat,b2lat,b1py,b2py)); • }
  • 22. l • • • • • Testing Campus Maps package com.simexusa.campusmaps_full; import com.simexusa.campusmaps_full.CampusMap; import com.simexusa.campusmaps_full.TranslatorUtility; import junit.framework.TestCase; public class TestTranslatorUtility extends TestCase { • protected void setUp() throws Exception { • super.setUp(); • } • public void testTranslateLatToY() { • double b1lat = 35.302518; • double b2lat = 35.299365; • int b1py = 445; • int b2py = 840; • Test complicated methods • double latitude = 35.299812; • assertEquals(784,TranslatorUtility.latToCoordinate(latitude,b1lat,b2lat,b1py,b2py)); • }
  • 23. l Testing Campus Maps • public void testSplit2() { • String s = "go+180"; • String [] results = s.split("+"); • assertEquals(results[0],"go"); • assertEquals(results[1],"180"); • } • Explore library API’s • Verify it works like I expect • public void testParser() { • CampusMap [] maps = TranslatorUtility.parseMapData( • "Bethel College|http://www.bethelks.edu/map/bcmap.png|” + • “39.298664|39.296903|-76.593761|-76.590527|383|614|171|352n"); • assertEquals(maps[0].title,"Bethel College"); • } • Functional tests • This one gets data from the web • public void testGetMaps() { • CampusMap[] myCampusMaps = new CampusMap[5]; • TranslatorUtility.retrieveMapData("http://simexusa.com/cm/fav5defaultmapdata.txt", • myCampusMaps); • assertEquals(myCampusMaps[0].title,"Cal Poly - SLO"); • }
  • 24. l TDD in Software Development Lifecycle
  • 25. l l What is Test-Driven Development? TDD is a design (and testing) approach involving short, rapid iterations of l Unit Test l Code l Refactor
  • 26. l l l What is Refactoring? Changing the structure of the code without changing its behavior l Example refactorings: l Rename l Extract method/extract interface l Inline l Pull up/Push down Some IDE’s (e.g. Eclipse) include automated refactorings
  • 27. l Test-Driven Development l Short introduction1 l Test-driven development (TDD) is the craft of producing automated tests for production code, and using that process to drive design and programming. For every tiny bit of functionality in the production code, you first develop a test that specifies and validates what the code will do. You then produce exactly as much code as will enable that test to pass. Then you refactor (simplify and clarify) both the production code and the test code. • 1. http://www.agilealliance.org/programs/roadmaps/Roadmap/tdd/tdd_index.htm
  • 28. l l Some Types of Testing Unit Testing l l l l Testing individual units (typically methods) White/Clear-box testing performed by original programmer Integration and Functional Testing • and may help here l Testing interactions of units and testing use cases Regression Testing l l Testing previously tested components after changes Stress/Load/Performance Testing l l • TDD focuses here How many transactions/users/events/… can the system handle? Acceptance Testing l • and here Does the system do what the customer wants?
  • 29. l l l l TDD Misconceptions There are many misconceptions about TDD They probably stem from the fact that the first word in TDD is “Test” TDD is not about testing,TDD is about design l Automated tests are just a nice side effect
  • 30. l l l Functional Testing ActivityInstrumentationTestCase2 l Allows us to create/start an Activity l Get Views from the Activity (e.g. Buttons) l Run things on the UI thread (e.g. click Buttons) l Perform asserts in JUnit Other options l http://code.google.com/p/autoandroid/ l Formerly Positron l Android + Selenium = Positron
  • 31. • public class FunctionalTest extends • ActivityInstrumentationTestCase2<AdvancedJokeList> { • public FunctionalTest() { super("edu.calpoly.android.lab2", AdvancedJokeList.class);} • protected void setUp() throws Exception { super.setUp(); } • public void testAddJoke() { • ArrayList<Joke> m_arrJokeList = null; • m_arrJokeList = this.retrieveHiddenMember("m_arrJokeList", • m_arrJokeList,getActivity()); • assertEquals("Should be 3 default jokes",m_arrJokeList.size(),3); • getActivity().runOnUiThread(new Runnable() { • public void run() { • AdvancedJokeList theActivity = (AdvancedJokeList)getActivity(); • EditText et = (EditText)theActivity. • findViewById(edu.calpoly.android.lab2.R.id.newJokeEditText); • Button bt = (Button)theActivity. • findViewById(edu.calpoly.android.lab2.R.id.addJokeButton); • et.setText("This is a test joke"); • bt.performClick(); • }}); • getInstrumentation().waitForIdleSync(); // wait for the request to go through • assertEquals("Should be 4 jokes now",m_arrJokeList.size(),4); • assertEquals("Ensure the joke we added is really there", • m_arrJokeList.get(3).getJoke(),"This is a test joke"); • }
  • 32. • @SuppressWarnings("unchecked") • public <T> T retrieveHiddenMember(String memberName, T type, Object sourceObj) { • Field field = null; • T returnVal = null; • try {//Test for proper existence • field = sourceObj.getClass().getDeclaredField(memberName); • } catch (NoSuchFieldException e) { • fail("The field "" + memberName + • "" was renamed or removed. Do not rename or remove this member variable."); • } • field.setAccessible(true); • • • • • • try {//Test for proper type returnVal = (T)field.get(sourceObj); } catch (ClassCastException exc) { fail("The field "" + memberName + "" had its type changed. Do not change the type on this member variable."); }
  • 33. • • • • • • • • • // Boiler Plate Exception Checking. If any of these Exceptions are // thrown it was because this method was called improperly. catch (IllegalArgumentException e) { fail ("This is an Error caused by the UnitTest!n Improper user of retrieveHiddenMember(...) -- IllegalArgumentException:n Passed in the wrong object to Field.get(...)"); } catch (IllegalAccessException e) { fail ("This is an Error caused by the UnitTest!n Improper user of retrieveHiddenMember(...) -- IllegalAccessException:n Field.setAccessible(true) should be called."); } return returnVal; }
  • 34. l l Monkey Random stress testing l l l l l From http://d.android.com/guide/developing/tools/monkey.html When the Monkey runs, it generates events and sends them to the system. It also watches the system under test and looks for three conditions, which it treats specially: If you have constrained the Monkey to run in one or more specific packages, it watches for attempts to navigate to any other packages, and blocks them. If your application crashes or receives any sort of unhandled exception, the Monkey will stop and report the error. If your application generates an application not responding error, the Monkey will stop and report the error. • adb shell monkey -p edu.calpoly.lab2 -v 500
  • 35. l l Android SDK documentation l l http://developer.android.com/reference/junit/framework/T estCase.html Tutorial: l l TDD and Android Resources http://dtmilano.blogspot.com/2008/01/test-drivendevelopment-and-gui-testing.html Blogs: l l http://dtmilano.blogspot.com/search/label/test%20driven %20development http://jimshowalter.blogspot.com/2009/10/developingandroid-with-multiple.html