Unit Testing (ppt)
Upcoming SlideShare
Loading in...5
×
 

Unit Testing (ppt)

on

  • 8,044 views

 

Statistics

Views

Total Views
8,044
Views on SlideShare
8,037
Embed Views
7

Actions

Likes
2
Downloads
211
Comments
1

1 Embed 7

http://www.slideshare.net 7

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Unit Testing (ppt) Unit Testing (ppt) Presentation Transcript

  • Writing a Unit test Using JUnit
    • At the top of the file include:
    import junit.framework.TestCase;
    • The main class of the file must be:
    public Must extend TestCase
    • Methods of this class, in order to be run automatically when the Test command is invoked, must:
    Be public return void Take no arguments Have a name beginning with “test”
  • Writing a Unit test using JUnit
    • Test methods in this class can call any of the following methods (among others):
    void assertTrue(String, boolean) void assertEquals(String, int, int) void fail(String) Issues an error report with the supplied String if the boolean is false Issues an error report with the supplied String if the two integers are not equal. The first int is the expected value, the second, the actual (tested) value. This method can be called with primitive or Objects (using their equals( ) method for comparison. This immediately causes the test to fail and issue an error report with the supplied String.
  • Writing Unit Tests using JUnit Example: Suppose we are writing a Calculator class that operates on pairs of numbers. Before writing the class, write some tests for it. Then write the Calculator class, compile it and the test class, and see if your Calculator code passes the tests you have set for it. If so, add more tests to check other cases that you discover in the process of writing and validating your code. Continue until you are satisfied that your code is correct and complete.
  • Example of using JUnit import junit.framework.TestCase; public class CalculatorTest extends TestCase { public void setUp( ) {Calculator calc = new Calculator( );} public void testAddition ( ) { // add 3 + 4 int expected = 7 int actual = calc.add(3, 4); assertEquals(“Adding 3 + 4 “, expected, actual); } public void testDivision( ) { try { calc.divide(2, 0); fail (“Should have thrown an Exception”); } catch (ArithmeticException e) { System.out.printLine(“Good! Divide by zero exception caught”); } Use method assertEquals to compare expected and actual results Test class extends TestCase Find actual result returned by Calculator method
  • Running the Test Once the test code and the unit (class) to be tested have been written and compiled, you can run the test in DrJava by simply clicking on the Test button in the top Toolbar. Test Progress Show Stack Trace All tests completed successfully. Die DieTest Die Test testRoll (test code is located in this window) Javadoc Test Reset Compile All Interactions Console Compiler Output Test Output
  • Running the Test Alternatively, one can manually control the execution of the test program and select which of the test methods to select by including the following method: public static Test suite( ) { TestSuite suite = new TestSuite( ); suite.addTest(new <class name>(“<method name>”) ); ………………………………… return suite; } Must import Test and TestSuite from junit.framework package Additional information about using JUnit can be found in the JUnit Cookbook at http:// junit . sourceforge .net/doc/cookbook/cookbook. htm
  • If the Test Fails A list of test failures is displayed in the Test Output tab in the bottom window similarly to compiler errors. To view a Stack Trace, right-click on the failure in the Test Output tab and select the Show Stack Trace button.
  • Running the Test in Eclipse 1. Create the unit (class) to be tested – Calculator, and test class -- CalculatorTest
    • Right click on the source file – CalculatorTest.java, and choose:
    • RunAs  JUnitTest in the popup menu.
    A window similar to the one on the left will appear on the left of the screen over where the Package Explorer normally appears If all of the tests complete successfully a green bar will appear in the window.
  • Running JUnitTest in Eclipse If one or more of the tests fail, a red bar appears in the window and a stack trace appears in the text area at the bottom of the window.
  • JUnit 4 in NetBeans Major Differences between JUnit 3.8 and JUnit 4 JUnit 3.8 JUnit 4.x import junit.framework.TestCase; //uses junit.framework.* import org.junit.Before; import org.junit.Ignore; import org.junit.Test; //uses org.junit.* //test methods must begin with //the identifier testXXXX, be void, and take no parameters JUnit 4 uses annotations instead @Test //must have at least one public void rollDice( ) {…} //does not have to start with test Must inherit from (and import) classAssert //There are two new assert methods public static void assertEquals(String mssg, Object[] expecteds, Object[] actuals); public static void assertEquals(Object[] expecteds, Object[] actuals);
  • Additional JUnit 4 Features JUnit 4 uses autoboxing to replace all the assertEquals (primitive, primitive) with assertEquals (Object, Object) You can use the assert keyword as you would assertEquals assertEquals(calculator.getResult( ), 5); OR assert calculator.getResult( ) == 5; Fixtures Methods to initialize and release any common objects during tests JUnit 3.8 JUnit 4 @Override protected void setUp( ) {…} //overrides method in TestCase //also used for method tearDown() @Before public void clearCalculator( ) {…} //method can be called by any name //also uses @After annotation with any //method name when tear down is needed.
  • Example of JUnit 4 Test import static org.junit.Assert.*; public class CalculatorTest { private static Calculator calculator = new Calculator( ); @Before public void clearCalculator( ) { calculator.clear( ); } @Test public void add( ) { calculator.add(1); calculator.add(1); assertEquals(calculator.getResult( ), 2); } @Test (expected = ArithmeticException.class) public void divideByZero( ) { calculator.divide(0); } @Ignore (“not ready yet”) @Test public void multiply( ) { calculator.add(2); calculator.multiply(5); assert calculator.getResult( ) == 10; } Fails if no exception or other type of exception is thrown Replaces fail(“message”) in 3.8 No need to extend a base class setUp Some tests can be performed before all methods are implemented Alternate to assertEquals
  • Running JUnit Tests in NetBeans Assume: You have created a Project called QueueTesting and in that project have a package called queueclasses that contains Queue.java (an interface), QueueUnderflowException.java , and QueueADT.java (currently a stub that implements Queue) Step 1: right-click on QueueADT node in Projects window Step 2: choose Tools -> Create JUnit Tests in the next window (2 nd from bottom) Step 3. Click OK with the default options (first time if given choice for version of JUnit, enter JUnit 4.1 and continue dialog – click OK) Step 4: A class QueueADTTest.java is created in TestPackages.queueclass and it appears in the Edit window in the IDE. Notice the org.junit imports as described previously! The class contains empty methods with the annotations @Before,@BeforeClass, @After, and @AfterClass  set up and/or tear down before and after each test (probably not used in any of your applications). It also has created @Test methods for each of the public Queue methods. You will need to modify these. Step 5: Right-click on QueueTesting project in the Projects Window->Test (to run)
  • Test Driven Development (TDD)
    • Always write the test before writing the code!
    • The tests will actually get written – It is human nature to avoid writing unit tests after the code has been written. The programmer may rationalize that the code is correct and a time consuming test program is not needed.
    • Programmer satisfaction – If the test is written first the programmer feels a need to write code to “pass the test” and gets a satisfaction out of doing so.
    • Clarification of detailed interface and behavior – As you write the test code you must imagine that the code for the class you are testing actually exists. This makes you think through the details of the public view of the method.
    • Provable, repeatable, automated verification – Over time the test base builds. The early investment in writing tests first pays dividends later as the size of the application grows.
    • The confidence to change things – If a developer needs to change one of the existing classes, there are unit tests available that can be run to provide immediate feedback of whether the change produced an error.
  • Understanding Software’s Environment Operating System kernel UI File System API Application under test
  • Understanding Software’s Environment If an application makes a request of the OS – for example, to allocate memory – it must check that that request has been successfully completed, and assert the appropriate error condition if it has not. Disks can get full and networks congested. What happens to our software system when the expected resources are not available? Software must be tested under normal operating conditions, not in a vacuum. Normal operating conditions include situations in which the external environment becomes stressed.