• No results found

JUnit. Introduction to Unit Testing in Java

N/A
N/A
Protected

Academic year: 2021

Share "JUnit. Introduction to Unit Testing in Java"

Copied!
19
0
0

Loading.... (view fulltext now)

Full text

(1)

JUnit

(2)
(3)

What Does a Unit Test Test?

 The term “unit” predates the O-O era.

 Unit – “natural” abstraction unit of an O-O

system: class or its instantiated form, object.

 Unit Tests – verify a small chunk of code,

typically a path through a method or function.

(4)

How Do We Unit Test?

 Print Statements (diffs against benchmarks)  Debuggers – examine variables, observe

execution paths.

 Typically done by unit developer.

 Best benefit if running of tests is

automated

.  Tests best run in isolation from one another.  Tests built incrementally as product code is

(5)

The Typical Test Cycle

 Develop a suite of test cases

 Create some test fixtures to support the running

of each test case.

 Run the test – capture test results.  Clean-up fixtures, if necessary.

(6)

Why is Unit Testing Good?

 Identifies defects early in the development cycle.  Many small bugs ultimately leads to chaotic

system behavior

 Testing affects the design of your code.  Successful tests breed confidence.

 Testing forces us to read our own code – spend

more time reading than writing

 Automated tests support maintainability and

(7)

Why Don’t We Unit Test?

 “Coding unit tests takes too much time”  “I’m to busy fixing bugs to write tests”

 “Testing is boring – it stifles my creativity”  “My code is virtually flawless…”

 “Testing is better done by the testing

department”

 “We’ll go back and write unit tests after we get

(8)

What is JUnit?

 JUnit is an open source Java testing framework

used to write and run repeatable tests.

 It is an instance of the xUnit architecture for

unit testing frameworks.

 JUnit features include:

 Assertions for testing expected results

 Test fixtures for sharing common test data

 Test suites for easily organizing and running tests  Graphical and textual test runners

(9)

JUnit Under the Hood

Originally written by Kent Beck and Erich Gamma. – design patterns.

An offspring of a similar framework for Smalltalk (SUnit)

A common xUnit

architecture has evolved and has been implemented in a variety of languages.

(10)

The JUnit Test Template

 Create a test class that extends TestCase

 Create a testxxx() method for each individual

test to be run.

 Create a test fixture – resources needed to

support the running of the test.

 Write the test, collect interesting test behavior  Tear down the fixture (if needed)

(11)

SimpleTest

import java.util.*;

import junit.framework.*;

public class SimpleTest extends TestCase{ public void testEmptyCollection() {

Collection testCollection = new ArrayList(); assertTrue( testCollection.isEmpty());

}

public static void main(String args[]){

junit.textui.TestRunner.run(SimpleTest.class); }

(12)

Key JUnit Concepts

 assert -

 assertEquals( expected, actual ) – also NotEquals  assertNull( actual result ) – also NotNull

 assertTrue( actual result) - also False

 failures –

 Exceptions raised by asserts (expected)

 errors –

(13)

Test Hierarchies

 JUnit supports test hierarchies

 Test Suite-A  Test Case1  Test Case2  Test Suite-B  Test Case3  Test Suite-C ( and so on …)

(14)

 If all tests pass, green bar!

Copyright © Andrew Meneely 14

(15)

Sometimes you expect an exception

1. First, run the code that should cause an exception 2. Catch the specific exception you expect

3. If that exception is not thrown, then fail the test with fail(“message”)

4. Assert the exception’s message, in the catch block

Copyright © Andrew Meneely 15

(16)

 Every day you are coding, do the following:

 Write code

 Write unit tests for that code

 Doesn’t need to be exhaustive – hit the three types  Fix unit tests.

 Go back to writing code

 Green bar every day. No excuses.

16

(17)

More…

 TDD / TFD ???

 Test Driven Design  Test First Design

 JUnit provides support for these agile techniques,

but JUnit is lifecycle agnostic

 Extensions for J2EE applications  What about GUI’s? – JUnit limited

(18)

 An advanced skill that takes years to master  General outline of events

1. Write a unit test.

2. You can’t run your unit test because it doesn’t compile… you

haven’t written that class yet. Write a stub.

3. Run your test again. Test runs, but fails because the class does

nothing.

4. Implement the simplest possible solution (e.g. hardcode) to make

that unit test pass.

5. Run all of your unit tests again. Fix until green bar. 6. Refactor (e.g. extract constants, methods, etc.). 7. Run all of your unit tests again. Green bar!

8. Go back to step 1 (or 3 if you have more ways to test that one

method).

Copyright © Andrew Meneely 18

(19)

Resources

 JUnit: www.junit.org  Testing Frameworks : http://c2.com/cgi/wiki?TestingFramework  cppUnit: http://cppunit.sourceforge.net/doc/1.8.0/index.html  SUnit: http://sunit.sourceforge.net/

 Unit Testing in Java – How Tests Drive the Code, Johannes Link  Test-Driven Development by Example, Kent Beck

 Pragmatic Unit Testing in Java with JUnit, Andy Hunt & Dave Thomas

 “Learning to Love Unit Testing”, Thomas & Hunt:

References

Related documents

(B) the adsorption at a single site on the surface may involve multiple molecules at the same time.. (C) the mass of gas striking a given area of surface is proportional to the

The purpose was to extend DNS conducted between two parallel plane walls to flows with a range of pressure gradients, relative to the common case of Poiseuille flow which has only

In the past, the Codex Alimentarius Commission Codex was the agency primarily responsible for the development of public international food safety rules, although the World

As the name implies, this menu allows you to take point data in a shapefile and create gridfiles where each grid cell takes a value calculated based on the points that are

When the Floor Trader comes to the Trading Area and asks to buy or sell shares or dollars, a share price or exchange rate, and a buy or sell amount is agreed by referring to

Moreover, while 47.8 percent of the pensions that hold some company stock are 401(k) plans, only 8.7 percent make their 401(k) plan a KSOP by adding ESOP status to the portion of

Western Ukraine exposed national art to Polish and Austrian influences. Already in the works of Modernist artists one can find reminiscences to predominant

From the rate of hydrogen evolution values, the inhibition efficiencies of the plant extract on the corrosion of mild steel in 5.0 M H 2 SO 4 solutions in the absence (blank)