You are on page 1of 46

TEST DRIVEN

DEVELOPMENT
Test-Driven Development
Quotes
Kent Beck said “Test-first code tends to be more cohesive
and less coupled than code in which testing isn’t a part
of the intimate coding cycle”

“If you can’t write a test for what you are about to code,
then you shouldn’t even be thinking about coding”
TDD Overview
• Made popular by Extreme Programming

• Method of developing software not just testing software

• Software is Developed in short iterations

• Unit Tests are developed FIRST before the code


TDD Overview
• How It Works –
1. Add a Test
• Use Cases / User Stories are used to understand the
requirement clearly
2. Run all tests and see the new one fail
• Ensures test harness is working correctly
• Ensures that test does not mistakenly pass
3. Write some code
• Only code that is designed to pass the test
• No additional functionality should be included because it
will be untested
TDD Overview
4. Run the automated tests and see them succeed
• If tests pass, programmer can be confident code meets all
tested requirements

5. Refactor code
• Cleanup the code
• Rerun tests to ensure cleanup did not break anything

Repeat
Test First vs. Test Last
• Pick a piece of functionality • Pick a piece of functionality
• Write a test that expresses a small • Write production code that
task that fails implements entire functionality
• Write production code until test • Write tests to validate all
passes functionality
• Run all tests • Run all tests
• Rework code until all tests pass • Rework code until all tests pass
• Repeat
Test First vs. Test Last
TDD Benefits
• Instant Feedback
• Developer knows instantly if new code works and if it
interferes with existing code [1]

• Better Development Practices


• Encourages the programmers to decompose the problem into
manageable, formalized programming tasks [1]
• Provides context in which low-level design decisions are made
[1]
• By focusing on writing only the code necessary to pass tests,
designs can be cleaner and clearer than is often achieved by
other methods [4]
TDD Benefits
• Quality Assurance
• Having up-to-date tests in place ensures a certain level of
quality
• Enables continuous regression testing
• TDD practices drive programmers to write code that is
automatically testable
• Whenever a software defect is found, unit test cases are
added to the test suite prior to fixing the code
TDD Benefits
• Lower Rework Effort
• Since the scope of a single test is limited, when the test fails,
rework is easier
• Eliminating defects early in the process usually avoids
lengthy and tedious debugging later in the project
• “Cost of Change” is that the longer a defect remains the
more difficult and costly to remove
TDD Limitations

• Counterproductive and hard to learn


• Difficult in Some Situations
• GUIs, Relational Databases, Web Service
• Requires mock objects
• TDD does not often include an upfront design
• Focus is on implementation and less on the logical structure
TDD Limitations
• Difficult to write test cases for hard-to-test code
• Requires a higher level of experience from programmers

• TDD blurs distinct phases of software development


• design, code and test
Test-Driven Development (TDD)
• Idea: Test First!
• Write unit tests before functional code
• Typically blackbox tests
Iterative Development Process

Re

is
Analys
qu
ire
m

n
en

igs
ts
n

De
Pla t io
Initial nni
ng ent a
Planning le m
Im p

TDD combines
Test
ing
it on
u a
a l
Ev
Deployment
Running Example:
Preorder Coffee with Gift Card
US and Tasks

Start with
Task 1
Further Break Down the Task
• Represent order info
• Represent gift card info
• Represent receipt info

*Although these might have been tasks, they’re very small, so it


made more sense to combine them into a larger task
Next Step: Write Test Code
Rule #1: Your test should fail before you
implement any code
• Establishes a measure of success
• Promotes programming incrementally
Next: Write code to make the test pass
Rule #2: Implement the simplest code possible
to make the test pass
• Also helps to promote incremental programming
• By focusing on small bits of code

• Helps resist urge to add unwanted extras


Test-Driven Development Cycle
Next (Red): Test order information
In writing the test, you design the class
interface — just enough interface!
Next (Green):
Implement
the interface
you designed
for the test
If in the process of building up classes, you
realize your design could be improved, then
REFACTOR!
… and continue going around and around …
As you go, you expand upon the systems
capabilities
• You might do a test for each of these cases:
• A gift card with more than enough to cover the cost of the order
• A gift card without enough to cover the cost of the order An
invalid gift card number
• A gift card with exactly the right amount
• A gift card that hasn’t been activated
• A gift card that’s expired
Pros/Cons of TDD
• Pros:
• Yields lots of test cases
• More tests leads to increased confidence

• Cons:
• False sense of confidence?
• Non-TDD folks may not understand why writing so many
tests and not functionality

Despite cons, TDD is a widely advocated practice


JUNIT
UNIT TESTING
JUNIT 4
• JUnit 4 is one of the most popular unit testing framework which has
a significant role in the test-driven development process. In this JUnit
4 tutorial, we will understand and see examples of the below topics.
• JUnit annotations like @Test, @Before, @BeforeClass, @After,
@AfterClass, etc…
• JUnit assertions like assertEquals, assertTrue, assertFalse, etc…
• JUnit test execution order
• Assertion and annotation examples
• JUnit suites
JUnit 4 Tutorial Prerequisites
Development Kit: JAVA JDK
Java Test Runner: JUnit (http://junit.org/)
IDE: IntelliJ (I prefer IntelliJ) also you can go with Eclipse or Netbeans

Nice to have: Before starting the JUnit tutorial, it is nice to have basic


knowledge of JAVA or any other object-oriented programming
language.
JUnit 4 Naming Conventions
• In general, test classes’ names should be ended with “Test” suffix.
Also, it is highly recommended to give a meaningful name for your
test classes such as FirefoxOrderCheckTest, ChromeLoginTest, etc…
In this way, you can easily understand the functionalities of test
classes.
Defining a Test in JUnit 4
• To start a JUnit test, you need to annotate a method with @Test annotation.
• There are many annotations in Junit and I will explain them in the below
section but
• the most critical annotation is “@Test” annotation. This indicates that the
following method is a test method.
• In your test methods, you use “assert” statements to check the conditions
that you are testing.
• It is a very good habit to write a clear message in assert statements that
help us to understand the problems easily.
• I also explained them in the Assertions section.
Annotations – Junit 4
Annotation Description

@Test The @Test annotation indicates the following method as a test method.
public void method() The following method has to be declared as public void

@Before This method is executed before each test.


It is generally using for setting necessary preconditions.
public void method() The following method has to be declared as public void

@After This method is executed after each test.


public void method() It is used to delete temporary data, restore default settings.
The following method has to be declared as public void

@BeforeClass The following static method is executed once, before the start of all tests.
public static void method() It is generally using for highly intensive operations such as DB connections.
The following method has to be declared as public static void

@AfterClass The following static method is executed once after all tests have been completed.
public static void method() It is generally using for clean-up activities such as disconnect from a database.
The following method has to be declared as public static void

@Ignore This annotation is useful when you want temporarily disable the execution of a specific test.
public static void method() The following method has to be declared as public static void

@Test (expected = Exception.class) If the method does not throw the given exception, the test will fail.

@Test(timeout=500) If the method takes longer than 500 milliseconds, the test will fail.
Annotations – Junit 4
Assert Methods & Description & Syntax Assert Methods & Description &
void assertEquals (“Message”, boolean expected, boolean Syntax
1
actual) 5 void assertNotNull(“Message”, Object object)
It compares that the given two values are the same. It checks that the object is not null
  Syntax: assertEquals(“Str1 is not equal to str 2”, str1, str2);   Syntax: assertNotNull(“Object is NULL! Pls check
2 void assertTrue(“Message”, boolean condition) it!”, obj);
It checks that the boolean condition is true. 6 void assertSame(“Message”, boolean condition)
  Syntax: assertTrue(“Bolean expression is not TRUE! Please It checks that two objects refer to the same
check it!”, val1 < val2);   object
3 void assertFalse(“Message”, boolean condition) Sytnax: assertSame(obj1,obj2);
It checks that the boolean condition is false. 7 void assertNotSame(boolean condition)
  Sytnax: assertTrue(“Bolean expression is not FALSE! Please It checks that two objects do not refer to the
check it!”, val1 < val2);   same object
4 void assertNull(“Message”, Object object) Syntax: assertNotSame(obj1,obj2);
It checks that the object is null
  Syntax: assertNotNull(“Object is not NULL! Pls check it!”,
obj);
Test execution order • JUnit tests are running in an arbitrary order. If
you want to run your tests in a fixed order,
you should
use @FixMethodOrder(MethodSorters.NA
ME_ASCENDING) annotation. With this
annotation, you can lexically sort and test the
methods in ascending order. It is shown below
screenshot.
Annotation Example

• When you run the below code, you will see that
• @BeforeClass runs only once before the all tests started
• @Before runs before each test started
• @Test defined attached method is a test method.
• @After runs after each test finished
• @AfterClass runs only once after all tests are finished.
• In the below code, I used “@FixMethodOrder(MethodSorters.NAME_ASCENDING)” annotation and lexically
ordered test names to run the tests in lexical order.
• I mean that all test names are started with T01_…, then T02_…, then T03…
• By using “@FixMethodOrder(MethodSorters.NAME_ASCENDING)” annotation, these test cases will run in the
following order T01 → T02 → T03

• REFER: TDDAnnotateEg in Eclipse


Assertion Example
• In the below example, I wanted to show that all assertions that I
explained in the assertions section. You can find detailed information
in comment lines. When you run the below code all assertions will
pass. Also, you can play with actual and expected values and will see
what is going to happen according to your changes.

You might also like