Unit Testing Bartosz Walter Software Engineering Lecture XXX.

Slides:



Advertisements
Similar presentations
JUnit Tutorial Hong Qing Yu Nov JUnit Tutorial The testing problems The framework of JUnit A case study JUnit tool Practices.
Advertisements

Unit Testing Australian Development Centre Brisbane, Australia.
Practice Session 5 Java: Packages Collection Classes Iterators Generics Design by Contract Test Driven Development JUnit.
Chapter 1 Writing a Program Fall Class Overview Course Information –On the web page and Blackboard –
Software Engineering Implementation Lecture 3 ASPI8-4 Anders P. Ravn, Feb 2004.
Slides adapted from Alex Mariakakis, with material from Krysta Yousoufian, Mike Ernst, and Kellen Donohue Section 4: Graphs and Testing.
Yoshi
J-Unit Framework.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
T ESTING WITH J UNIT IN E CLIPSE Farzana Rahman. I NTRODUCTION The class that you will want to test is created first so that Eclipse will be able to find.
Ch. 2 Exploring core JUnit. This chapter covers ■ Using the core JUnit classes ■ Understanding JUnit mechanisms ■ Understanding the JUnit lifecycle.
Inheritance Inheritance Reserved word protected Reserved word super
Approach of Unit testing with the help of JUnit Satish Mishra
JUnit. What is unit testing? A unit is the smallest testable part of an application. A unit test automatically verifies the correctness of the unit. There.
1 Software Testing and Quality Assurance Lecture 23 – JUnit Tutorial.
JUnit, Revisited 17-Apr-17.
JUnit Introduction and Advanced Features. Topics Covered  Junit Introduction  Fixtures  Test Suites  Currency Example.
24-Jun-15 JUnit. 2 Test suites Obviously you have to test your code to get it working in the first place You can do ad hoc testing (running whatever tests.
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.
Testowanie kodu Bartosz Baliś, Na podstawie prezentacji Satisha Mishra Iana Sommerville Erica Braude.
CS 635 Advanced Object-Oriented Design & Programming Spring Semester, 2006 Doc 2 Terms & Testing Jan 24, 2006 Copyright ©, All rights reserved SDSU.
Presentation Outline What is JUnit? Why Use JUnit? JUnit Features Design of JUnit Downloading JUnit Writing Tests – TestCase – TestSuite Organizing The.
14-Jul-15 JUnit 4. Comparing JUnit 3 to JUnit 4 All the old assertXXX methods are the same Most things are about equally easy JUnit 4 makes it easier.
Unit Testing Discussion C. Unit Test ● public Method is smallest unit of code ● Input/output transformation ● Test if the method does what it claims ●
Programmer Testing Testing all things Java using JUnit and extensions.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
© Dr. A. Williams, Fall Present Software Quality Assurance – JUnit Lab 1 JUnit A unit test framework for Java –Authors: Erich Gamma, Kent Beck Objective:
Lesson 7 Unit Testing /JUnit/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
Junit Training Chris Yeung 8 th Sept, Introduction JUnit is a regression testing frameworkJUnit is a regression testing framework Written by Erich.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
Computer Science and Engineering College of Engineering The Ohio State University JUnit The credit for these slides goes to Professor Paul Sivilotti at.
COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.
1 Object Oriented Programming Testing with Unit Testing & the JUnit tool Basic Refactoring techniques.
Unit testing Unit testing TDD with JUnit. Unit Testing Unit testing with JUnit 2 Testing concepts Unit testing Testing tools JUnit Practical use of tools.
The Java Programming Language
JUnit test and Project 3 simulation. 2 JUnit The testing problems The framework of JUnit A case study Acknowledgement: using some materials from JUNIT.
Introduction to JUnit 3.8 SEG 3203 Winter ‘07 Prepared By Samia Niamatullah.
JUnit Dwight Deugo Nesa Matic
ESO - Garching 23 June – 02 July, 2003 ACS Course JUnit for Java Unit Testing H. Sommer.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
JUnit Dwight Deugo Nesa Matic
A tool for test-driven development
JUnit Eclipse, Java and introduction to Junit. Topics Covered  Using Eclipse IDE  Example Java Programs  Junit Introduction.
JUnit A framework which provides hooks for easy testing of your Java code, as it's built Note: The examples from these slides can be found in ~kschmidt/public_html/CS265/Labs/Java/Junit.
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 11, Testing.
S Ramakrishnan1 Systems V & V, Quality and Standards Dr Sita Ramakrishnan School CSSE Monash University.
JUnit A Unit Testing Framework for Java. The Objective Introduce JUnit as a tool for Unit Testing Provide information on how to: Install it Build a test.
Unit, Regression, and Behavioral Testing Based On: Unit Testing with JUnit and CUnit by Beth Kirby Dec 13, 2002 Jules.
Justin Bare and Deric Pang with material from Erin Peach, Nick Carney, Vinod Rathnam, Alex Mariakakis, Krysta Yousoufian, Mike Ernst, Kellen Donohue Section.
1 JUnit. 2 Unit Testing with JUnit If code has no automated test case written for it to prove that it works, it must be assumed not to work. An API that.
Topic: Junit Presenters: Govindaramanujam, Sama & Jansen, Erwin.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Automated Testing with PHPUnit. How do you know your code works?
SWE 434 SOFTWARE TESTING AND VALIDATION LAB2 – INTRODUCTION TO JUNIT 1 SWE 434 Lab.
Software Construction Lab 10 Unit Testing with JUnit
Unit testing Java programs Using JUnit
This presentation is created for the course COP4331 at UCF
Computer Science 209 Testing With JUnit.
Accessing Files in Java
Junit with.
null, true, and false are also reserved.
Java Programming Language
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2004 Instructor: Patrice Chalin.
Credit to Eclipse Documentation
Introduction to JUnit IT323 – Software Engineering II
Joel Adams and Jeremy Frens Calvin College
TCSS 360, Spring 2005 Lecture Notes
JUnit Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from the Eclipse 3.0 and.
Chapter 20: Software Testing - Using JUnit, and Cobertura
JUnit Tutorial Hong Qing Yu Nov 2005.
Presentation transcript:

Unit Testing Bartosz Walter Software Engineering Lecture XXX

Agenda 1.JUnit – a unit testing library for Java 2.Guidelines for creating test cases 3.Smells in tests 4.Implementation tasks

Schemat klas jUnit TestCase Test TestSuiteTestResult RomanNumberTest

TestCase MyTest void testXXXX() void tearDown () void setUp ()   junit.framework.TestCase void testYYYY() void testZZZZ() void testWWWW() void testXXXX() void testYYYY() void testZZZZ() MyTest(name)

StudentTest.java Klasa i jej klasa testowa + testComputeLevel() + testGetAge() + testGetName() + tearDown () + setUp () + computeLevel() + getAge() + getName() Student.java Utworzenie instancji klasy Student Usunięcie instancji klasy Student – Student student

TestCase MyTest void testXXXX() void tearDown () void setUp ()   junit.framework.TestCase void testYYYY() void testZZZZ() void testWWWW() void testXXXX() void testYYYY() void testZZZZ() MyTest(name)

Simplest test possible... void tearDown () void setUp () void testSimple() public void setUp() { rn1 = new RomanNumber(5); rn2 = new RomanNumber(20); } public void testSimple() throws Exception { String str = rn1.toString(); assertEquals(str, "V"); } public void tearDown() { rn1 = null; rn2 = null; } RomanNumberTest (name) public RomanNumberTest(name){ super(name); }

Failure vs. error Failure:  anticipated violation of the test assertion  signals that the test actually fails Error:  unanticipated exception caught by the test runner  the test could not be run properly

Failure vs. error public void testNonexistentFileRead() throws IOException { try { File file = new File("doesNotExist.txt"); FileReader reader = new FileReader(file); assertEquals('a', (char) reader.read()); fail("Read from a nonexistent file?!"); } catch (FileNotFoundException success) {} } public void testExistingFileRead() throws IOException { // exists.txt created in setup(), perhaps File file = new File("exists.txt"); FileReader reader = new FileReader(file); assertEquals('a', (char) reader.read()); }

Basic functionality of a TestCase Groups of methods:  equality tests  void assertEquals([msg], expected, actual)  identity tests  void assertSame([msg], expected, actual)  void assertNotSame ([msg], expected, actual)  boolean tests  void assertTrue([msg], condition)  void assertFalse([msg], condition)  null tests  void assertNull([msg], object)  void assertNotNull([msg], object)  unconditional failure  void fail([msg])

Creating TestSuite s statically public class RomanNumberTest extends TestCase { public RomanNumberTest(String name) { super(name); } // testing methods public void testSimpleConv() {} public void testAddition() {} public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new MyTest("testSimpleConv")); suite.addTest(new MyTest("testAddition")); return suite; }

Creating TestSuite s dynamically public class RomanNumberTest extends TestCase { public RomanNumberTest(String name) { super(name); } // testing methods public void testSimpleConv() {} public void testAddition() {} public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(MyTest.class) return suite; }

Guidelines for creating TestCase s Don't use constructor for initializing the TestCase junit.framework.AssertionFailedError: Cannot instantiate test case: test1 at junit.framework.Assert.fail(Assert.java:143) at junit.framework.TestSuite$1.runTest(TestSuite.java:178) at junit.framework.TestCase.runBare(TestCase.java:129) at junit.framework.TestResult$1.protect (TestResult.java:100)... public class SomeTest extends TestCase { public SomeTest (String testName) { super (testName); // Perform test set-up }

Guidelines for creating TestCase s Don't use constructor for initializing the TestCase public class SomeTest extends TestCase { public SomeTest (String testName) { super (testName); } public void setUp() { // Perform test set-up } java.lang.IllegalStateException: Oops at bp.DTC.setUp(DTC.java:34) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect( TestResult.java:100)...

Guidelines for creating TestCases Don't assume the order in which tests within a TestCase are executed Avoid writing TestCases with side effects public class SomeTestCase extends TestCase { public SomeTestCase (String testName) { super (testName); } public void testDoThisFirst () { } public void testDoThisSecond () { }

Guidelines for creating TestCases Don't assume the order in which tests within a TestCase are executed Avoid writing TestCases with side effects public class SomeTestCase extends TestCase { public void testDoThisFirst () { } public void testDoThisSecond () { } public static Test suite() { suite.addTest(new SomeTestCase("testDoThisFirst";)); suite.addTest(new SomeTestCase("testDoThisSecond";)); return suite; }

Guidelines for creating TestCases Avoid using hardcoded resources Write self-contained tests Place tests in the same packages as source code public class SomeTestCase extends TestCase { public void setUp () { FileInputStream inp ("C:\\TestData\\dataSet1.dat"); //.. }

Guidelines for creating TestCases Avoid using hardcoded resources Write self-contained tests Place tests in the same packages as source code public class SomeTestCase extends TestCase { public void setUp () { InputStream inp = class.getResourceAsStream (this.getClass (), "dataSet1.dat"); }

Guidelines for creating TestCases Avoid time/locale-sensitive tests Date date = DateFormat.getInstance().parse("dd/mm/yyyy"); Calendar cal = Calendar.getInstance(); Cal.set(yyyy, mm-1, dd); Date date = Calendar.getTime(); Locale locale = Locale.getDefault();

Guidelines for creating TestCases Use JUnit assert/fail methods for throwing Exceptions Don't catch exceptions unless they are expected to be thrown public void exampleTest() { try { // do some testing } catch (SomeApplicationException ex) { fail ("Caught SomeApplicationException exception"); }

Guidelines for creating TestCases public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); try { Object o = emptyList.get(0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException success) { } If the test should pass on exception thrown, catch the exception within the test and place fail() if it is not thrown

Guidelines for creating TestCases public void exampleTest () throws SomeApplicationException { // do some test } Use JUnit assert/fail methods for throwing Exceptions Don't catch exceptions unless they are expected to be thrown

Guidelines for creating TestCases Beware of floating-point comparison errors assertEquals ("The result is different from what is expected", result, expected); assertEquals ("The result is different from what is expected", , 1/10.0); assertEquals ("The result is definitely different from what is expected ", result, expected, delta); assertEquals ("The result is definitely different from what is expected", , 1/10.0, 0.01);

Guidelines for creating TestCases Testing protected and private methods Protected:  Place the tests in the same package as the classes under test. Private:  avoid  use Java Reflection to call a private method

Guidelines for creating TestCases Organizing files in catalog | +--src | | | +--com | | | +--xyz | | | +--SomeClass.java +--test | +--com | +--xyz | +--SomeClassTest.java com.xyz.SomeClass com.xyz.SomeClassTest

Task 1 Write tests for existing code of RomanNumber class

RomanNumber class RomanNumber { // initialize with an Arabic year public RomanNumber(int number); // initialize with a Roman year public RomanNumber(String number); // return the Roman value public String toRoman(); // return the Arabic value public int toArabic(); // return a Collection of legal Roman symbols public static Collection getRomanSymbols(); }

Task 2 Implement RomanNumber class using test-first approach.

Testing first TestCase:  INPUT: 1, EXPECTED: "I" Implementation: String toArabic(int num) { return "I"; }

Testing first TestCase:  INPUT: 2, EXPECTED: "II" Implementation: String toArabic(int num) { if (num == 1) return "I"; else return "II"; }

Testing first TestCase:  INPUT: 3, EXPECTED: "III" Implementation: String toArabic(int num) { if (num == 1) return "I"; else if (num == 2) return "II"; else return "III"; }

Testing first TestCase:  INPUT: 3, EXPECTED: "III" Implementation: String toArabic(int num) { while (num-- > 0) result += "I"; return result; } Refactoring

Testing first TestCase:  INPUT: 4, EXPECTED: "IV" Implementation: String toArabic(int num) { if (num < 4) while (num-- > 0) result += "I"; return result; } return "IV"; }

Testing first TestCase:  INPUT: 5, EXPECTED: "V" Implementation: String toArabic(int num) { if (num < 4) while (num-- > 0) result += "I"; return result; } else if (num == 4) { return "IV"; } else { return "V"; }

Testing first TestCase:  INPUT: 6, EXPECTED: "VI" Implementation: String toArabic(int num) { if (num < 4) while (num-- > 0) result += "I"; return result; } else if (num == 4) { return "IV"; } else if (num == 5) { return "V"; } else return "VI"; }

Testing first TestCase:  INPUT: 8, EXPECTED: "VIII" Implementation: String toArabic(int num) { if (num < 4) while (num-- > 0) result += "I"; return result; } else if (num == 4) { return "IV"; } else { result = "V"; while (num-- > 5) result += "I"; return result; } Refactoring

Testing first TestCase:  INPUT: 9, EXPECTED: "IX" Implementation: String toArabic(int num) { // else if (num < 9) { result = "V"; while (num-- > 5) result += "I"; return result; } else { return "IX"; }

Testing first TestCase:  INPUT: 10, EXPECTED: "X" Implementation: String toArabic(int num) { // else if (num < 9) { result = "V"; while (num-- > 5) result += "I"; return result; } else (num == 9) { return "X"; } else { return "IX"; }

Testing first TestCase:  INPUT: 1976, EXPECTED: "MCMLXXVI" Implementation: private class ConvSymbols {int arabic, String roman} {{1,I}, {4,IV}, {5,V}, {9,IX}, {10,X}, {40,XL},...} String toArabic(int num) { for (int i = 0; i < sizeof(symbols); i++) { Symbol sym = symbols[i]; while (num >= symbol.arabic) { num -= symbol.arabic; result += symbol.roman; } Refactoring

Bibliography 1.JUnit, 2.Test Infected – Programmers love writing tests, testing.htm 3.JUnit Cook's Tour, cookstour.htm 4.Unit-testing Tools,

Q&A