Unit Testing with JUnit by nyut545e2

VIEWS: 4 PAGES: 26

									Unit Testing with JUnit

        Dave Elliman




             1
   The Philosophy
If code has no automated
       test cases to
      show it works,
   then the assumption
  must be that it doesn't
            2
Laws of Programming

 Murphy’s Law, “All programs have errors”
 Sod’s Corollary: “The errors will manifest
 at the least convenient moment”
 O'Toole's Commentary: “Murphy was an
 optimist”
 Jenkinson's Law: “It won't work”
 Brooke's Law: “Adding manpower to a late
 software makes it later”

                    3
Solution: Formal specification
  and program verification?
   Very time consuming
   Assumes stable requirements (not
   agile)
   Murphy says, “All formal proofs have
   errors”
   A major obstacle to refactoring
   Useful in its place (safety critical
   systems)
                       4
  Solution: Testing
Objection: Testing proves the presence of
errors, not their absence
Objection: It is impossible to test all paths,
and all variable values in non-trivial
programs
The alternative to growing old is not that
attractive. Same applies to testing
In practice TDD achieves very low defect
rates when used by a skilled team

                     5
Why use an integrated
     test suite?
 If you design the tests before the code,
 you can test thoroughly even if not
 exhaustively.
 Refactoring if a key idea in XP. It is the
 way to produce maintainable code.
 Integrated testing facilitates this.
 If the tests fail after you changed the
 code, YOU broke it! YOU fix it!

                     6
Benefits from writing
 tests before code
• A new mindset: One writes code only to
  correct a failing test
• You write your code to be testable which
  means you design it better
• Architecture is an emergent property
Why don’t people do this
        then?
 • They say they, “Don’t have the time”
 • Productivity is a function of the
    correctness and adaptability of you code
    base
 • If you don’t have test coverage it will have
    errors and be very hard to refactor
 • So “they” are right. It is a self-fulfilling
    prophecy. They won’t have the time.

                         8
Where to get JUnit

Junit was written by Erich Gamma and
Kent Beck
It is to be found in a fairly obvious place
  http://www.junit.org/index.htm

Open-source… free…
Use Xunit for other laguages (eg OCUnit)


                     9
A Hierarchy of terms

TestCase
  This is a fixture designed to run a set of Tests. It
  provides variables and objects that the tests need
TestSuite
  This is a set of related TestCases
Test
  A test



                       10
    Essential Classes
junit.framework.TestCase
   Allows running multiple tests
   Does all counting and reporting of errors
junit.framework.Assert
   A set of assert methods
   Test fails if the assert condition does not hold
   If a test fails it is counted and reported
junit.framework.TestSuite
   A collection of tests
   Uses Java introspection to find all the methods start with
   "test“ and have void parameters.
   TestSuite's run method executes all the tests
                             11
        Test Runners

Classes that run tests for a test case
  Accepts the name of a TestCase class as an
  argument
  If this class defines a static suite method it will be
  invoked and the returned test is run. Otherwise all
  the methods starting with "test" having no arguments
  are run.




                        12
      Getting Started

• Subclass TestCase class
• Define TestCase methods
• Run TestCase
        Using Junit (Create
             Fixture)
public class    complexTest extends TestCase {
    Complex c1;
    Complex c2;
    protected void setUp() {
        c1 = new Complex(7,3);
        c2 = new Complex(12,6);
    }
    protected void tearDown(){
    }
}
                           14
      Using Junit (Add Test
             Cases)
public void testAdd() {
    Complex result = c1.Add(new Complex(5,3));
    assertEquals(result.get_r(),c2.get_r());
    assertEquals(result.get_i(),c2.get_i());
}


public void testEqual(){
    assertTrue(!c2.Equal(c1));
    assertTrue(c1.Equal(new Complex(7,3)));
}

                              15
    Using Junit (Make Suite)

public static Test suite() {
    TestSuite suite = new TestSuite();
    suite.addTest(new ComplexTest(“testAdd”));
    suite.addTest(new ComplexTest(“testEqual”));
    return suite;
}




                           16
    Using Junit (Invoke)


public static void main(String[] args) {
     junit.textui.TestRunner.run(suite());
}




                    17
To summarise the steps
     in using Junit:
  Make sure the JUnit jar file is in your
  classpath
  Subclass TestCase
  If you need objects etc then override
  setUp() (remember capital U)
  Define your tests. Names begin with test…
  testAdd etc
  If you have several related TestCases then
  define a TestSuite

                      18
The Graphical UI




       19
UI on Failure




      20
Integrating JUnit with ant

   ant and Junit go together like a horse and
   carriage
   ant = build and deploy
   ant + JUnit = build, deploy and test
   ant has built-in support for JUnit



                      21
    Example… in build.xml

<target name = “test” depends = “compile”>
  <junit printsummary=“true”>
      <formatter type=“plain” usefile=“false” />
      <test name=“MyCodeTests” />
      <classpath>
             <pathelement location=“somewhere” />
      </classpath>

  </junit>
</target>



                                22
What does this do?

It runs the tests after compilation and
sends a report to the standard output
Would you prefer the output to go to a
web page?
  Change one line of the script as follows:
     <formatter type = “xml” />
     You get MyCodeTests.xml
     You can transform this to html with XSLT


                       23
     Can I do this in the ant
              file?
<junitreport todir=“./reports”>
  <fileset dir=“.”>
       <include name=“MyCodeTest*.xml”/>
  </fileset>
  <report format=“frames” todir=“./report/html” />
</junitreport>



Idea! Why not set up a script that runs ant every night for your
project. There will be a web page for all the team to look at
that shows the status of the tests. (unix at command. Windows
task scheduler – on Control Panel)
                                24
Is it really that EASY?

 Well I did skate over a couple of things… if
 you want to create web pages output:
   You need xslt.jar and junit.jar in the ant classpath
   Also optional.jar from:
      http://jakarta.apache.org/ant/index.html

 This is very simple to do. Just put all three
 jar files in ANT_HOME/lib


                        25
            Further reading

• Lots of articles at www.junit.org
• Beck and Gamma (1998) Test-Infected:
  Programmers Love Writing Tests, Java
  Report, July, pp. 37-50. Also available at:
   •   http://members.pingnet.ch/gamma/junit.htm

• Martin Fowler (1999) A UML Testing
  Framework, Software Development, April.
  Also available at:
   •   http://www.sdmagazine.com/breakrm/fr_feat4_thismonth.htm

                                  26

								
To top