Docsity

Study Guide for Exam - Introduction to Software Engineering | CS 3300, Exams of Software Engineering

Toggle sidebar
bg1
Unit Testing
Colin Potts
CS 3300. Fall, 2001
Agenda
• Testing: Definitions and objectives
• Black-box test case generation for units of
code
– Running test cases: scaffolding
• Clear-box/White-box/Glass-box testing
guidelines
• Planning testing
– When can/should you stop testing?
Importance of Testing
• Testing is most effort-intensive activity in
software projects
– But is still often stopped too early or curtailed in a
late project
• Scope of testing
– Unit testing = testing of individual modules
– Integration testing = testing of assemblies of
modules
• Syste m testing is the limiting case
Questions on Testing
• What is testing?
– Seeing whether a program compiles?
– Reading a program carefully?
– Proving that a program works?
• What is the difference between testing and
debugging?
• What gets tested?
– Entire system?
– Modules, one-by-one?
What you need for testing
• Something to test
– code & stubs for code that calls
• Test cases
–concrete inputs and expected outputs
• Some way of providing test case inputs
– drivers (including CLI + main program)
• An “oracle” for judging whether test cases
pass
– usually the specification and your judgment
Terminology
• Failures & faults
–Failure: Undesirable difference between observed &
expected behavior
–Fault/defect: Cause of failure
–Defect rate: Number of defects per 1000 lines of code
• Testing vs. debugging
–Testing: Systematically finding failures by running code
–Debugging: Finding & fixing defects in the code
•Black-box vs. “white-box” testing
– Do you have access to the code in producing test cases?
•Scaffolding: software to support testing
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Study Guide for Exam - Introduction to Software Engineering | CS 3300 and more Exams Software Engineering in PDF only on Docsity!

Unit Testing

Colin Potts

CS 3300. Fall, 2001

Agenda

• Testing: Definitions and objectives

• Black-box test case generation for units of

code

– Running test cases: scaffolding

• Clear-box/White-box/Glass-box testing

guidelines

• Planning testing

– When can/should you stop testing?

Importance of Testing

• Testing is most effort-intensive activity in

software projects

– But is still often stopped too early or curtailed in a

late project

• Scope of testing

– Unit testing = testing of individual modules

– Integration testing = testing of assemblies of

modules

  • System testing is the limiting case

Questions on Testing

• What is testing?

– Seeing whether a program compiles?

– Reading a program carefully?

– Proving that a program works?

• What is the difference between testing and

debugging?

• What gets tested?

– Entire system?

– Modules, one-by-one?

What you need for testing

• Something to test

– code & stubs for code that calls

• Test cases

– concrete inputs and expected outputs

• Some way of providing test case inputs

– drivers (including CLI + main program)

• An “oracle” for judging whether test cases

pass

– usually the specification and your judgment

Terminology

  • Failures & faults
    • Failure: Undesirable difference between observed &

expected behavior

  • Fault/defect : Cause of failure
  • Defect rate : Number of defects per 1000 lines of code
  • Testing vs. debugging
  • Testing : Systematically finding failures by running code
  • Debugging : Finding & fixing defects in the code
  • Black-box vs. “ white-box ” testing
  • Do you have access to the code in producing test cases?
  • Scaffolding : software to support testing

Testing

n Purpose

  • "Program testing can be used to show the presence of errors,

but never to show their absence" (Dijkstra)

  • Gain confidence in the system by failing to find defects

n Who tests?

  • Programmers should only release code with which they are

confident

  • But programmers are predisposed to believe their programs are

correct

  • Test each other’s code or use independent organization

Agenda

  • Testing: Definitions and objectives
  • Black-box test case generation for units of

code

  • Running test cases: scaffolding
  • Clear-box/White-box/Glass-box testing

guidelines

  • Planning testing
    • When can/should you stop testing?

Test Cases

Inputs Expected outputs

1, 2, 3, 4 2.

1 1

1, 2, 3, 4, 5 3

Format is a set of input conditions (may include

state information) and expected outputs.

Black box testing example

n You have to test a function that allegedly correctly categorizes triangles

  • Function accepts triple of

integers

  • No need to test the type of

the inputs

n Prepare a list of test cases

  • Example input triples
  • Expected return value

Equilateral

Isosceles

Scalene

Unfeasible

Requirement Without Necessary Errors

(Myers) A function that tells whether three

numbers produce an equilateral triangle

(whose sides are all equal), an isosceles

triangle (containing exactly two equal

sides) or a scalene triangle (a triangle

which is neither equilateral nor

isosceles).

A function that tells whether a triplet of numbers produces:

(1) an equilateral triangle (whose sides are all greater than

zero and equal), in which case it outputs ‘E’ at the prompt,

or

(2) an isosceles triangle (whose sides are greater than zero,

exactly two of which are equal, and which form a

triangle), in which case it outputs ‘I’ at the system, or

(3) a scalene triangle (whose sides are all greater than

zero, which form a triangle, and which is neither

equilateral nor isosceles), in which case it outputs ‘S’ at

the prompt, or

(4) no triangle, in which case it outputs ‘N’ at the prompt.

… More Complete

*** The following sequences occur commonly:

  • ge-aq-so
  • ge-sq-a-gq *.....
  • The following sequences have a high potential for defects:
  • ge-aq-aq-gq-so ..... /

/ Test C1: ge-aq-so / EncounterCharacter eC1M = new EncounterCharacter( "CharForTestC1" ); // method “ge” eC1M.adjustQuality(QUAL_STRENGTH, 40.0f ); // aq TestExecution.printReportToFile( outM, "Class test ge-aq-so", eC1M.sumOfQualities(), 100.0f ); // so

/ Test C2: ge-aq-aq-gq-so / EncounterCharacter eC2M = new EncounterCharacter( "CharForTestC2" ); // ge eC2M.adjustQuality(QUAL_STRENGTH, 40.0f ); // aq eC2M.adjustQuality(QUAL_STAMINA, 20.9876f ); // aq

Listing

page 4

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

TestExecution.printReportToFile( outM, "Class test ge-aq-aq-gq-so: part 1", eC2M.getQualityValue( QUAL_STAMINA ), 20.9876f ); // gq

TestExecution.printReportToFile( outM, "Class test ge-aq-aq-gq-so: part 2", eC2M.sumOfQualities(), 100.0f ); // so

*/ INVARIANT-ORIENTED TESTS

  • Check for the invariant “qualValueI[i] >=0”
  • -- after executing the sequences of methods executed above / boolean truthM = true; for( int i = 0; i < qualityTypeS.length; ++i ) { / Set truthM false if any entry in eC1M.qualValueI not >= 0 / truthM = truthM && ( eC1M.qualValueI[i] >= 0.0f ); } TestExecution.printReportToFile( outM, "Class test for the invariant 'qualValueI[i] >=0'", truthM, true );*

/ Conclude / outM.close(); System.out.println( "\nClass tests of EncounterChar class concluded." );

} // end of testEncounterCharacterClass

Listing

page 5 Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

/ Tests all the methods of this class one at a time

  • @param destinationP Location to write results.
  • @exception IOException If there’s a problem opening or accessing destinationP / public static void testEncounterCharacterMethods( String destinationP ) throws IOException { / Prepare for the test / FileWriter outM = new FileWriter( new File( destinationP ) ); System.out.println( "EncounterCharacter method test results on " + destinationP + "\n" );*

/ Tests for getEncounterCharacter() /

EncounterCharacter eCNorM = new EncounterCharacter( "qwerty" ); // normal TestExecution.reportToFile( outM, "GetCharacter Test 1: nominal value", eCNorM.getName(), "qwerty" );

EncounterCharacter eCNullM = new EncounterCharacter( null ); // null TestExecution.reportToFile( outM, "GetCharacter Test 2: null parameter", eCNullM.getName(), GameCharacter. DEFAULT_NAME);

Listing page 6

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

**String tooLongM = "1234567890123456789012345678901234567890"; EncounterCharacter eCTooLongM = new EncounterCharacter(tooLongM); // too long TestExecution.reportToFile( outM, "GetCharacter Test 3: Limit parameter values, "

  • "max name len = " + eCTooLongM .maxNumCharsInName(), eCTooLongM.getName(), tooLongM.substring(0, eCTooLongM.maxNumCharsInName()) );**

EncounterCharacter eCZeroM = new EncounterCharacter( "" ); // zero-len TestExecution.reportToFile( outM, "GetCharacter Test 4: zero-length", eCZeroM .getName(), GameCharacter. DEFAULT_NAME);

EncounterCharacter eCPuncM = new EncounterCharacter( "a+b" ); // bad chars TestExecution.reportToFile( outM, "GetCharacter Test 5: bad char '+' ", eCPuncM .getName(), GameCharacter. DEFAULT_NAME);

Listing page 7

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

/ Tests for indexOf() for every valid quality name. / for( int i = 0; i < qualityTypeS.length; ++i ) try { TestExecution.reportToFile( outM, "indexOf() Test 1." + i + ": valid name: " + qualityTypeS[i], indexOf(qualityTypeS[i]), i ); } catch( Exception eP ) { TestExecution.reportToFile( outM, "indexOf() Test 1: valid name: compare ", "indexOf('" + qualityTypeS[i] + "')", "with expected " + i ); }

/ Tests for indexOf() for an invalid quality name. / try { TestExecution.reportToFile( outM, "indexOf() Test 2: invalid name: zorch", indexOf("zorch"), -1 ); } catch( Exception eP ) { TestExecution.reportToFile( outM, "indexOf() Test 2: valid name: compare ", "indexOf("zorch")", "with expected -1" ); }

Listing page 8

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

/ Tests for setQuality() /

// Set up for test EncounterCharacter hank = new EncounterCharacter( "Hank" );

// Nominal value hank.setQuality(QUAL_STRENGTH , 10.3f ); TestExecution.reportToFile( outM, "setQuality() Test 1: nominal value", hank.getQualityValue( QUAL_STRENGTH ), 10.3f );

// Out of range value hank.setQuality( QUAL_PATIENCE, -6.2f ); TestExecution.reportToFile( outM, "setQuality() Test 2: nominal value", hank.getQualityValue(QUAL_PATIENCE ), 0.0f );

// Value below close-to-zero threshold. hank.setQuality( QUAL_STAMINA, getTolerance() * 0.9f ); TestExecution.reportToFile( outM, "setQuality() Test 3: value close to zero", hank.getQualityValue(QUAL_STAMINA), 0.0f );

Listing page 9

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

// Tests for adjustQuality().

// Set up for test and verify: Values should be 20 each. EncounterCharacter harvey = new EncounterCharacter( "Harvey" ); TestExecution.reportToFile( outM, "adjustQuality() test 0: verify that values add to 100", harvey.sumOfQualities(), 100.0f );

// Nominal adjustment harvey.adjustQuality(QUAL_STRENGTH , 30.0f ); // strength 30 rest 70/4 each TestExecution.reportToFile( outM, "adjustQuality() test 1: values sum to 100 after adjusting", harvey.sumOfQualities(), 100.0f ); TestExecution.reportToFile ( outM, "adjustQuality() test 2: values adjusted as commanded", harvey.getQualityValue(QUAL_STRENGTH ), 30.0f );

// Adjustment resulting in a zero value harvey.adjustQuality( QUAL_STAMINA, 99.0f ); TestExecution.reportToFile( outM, "adjustQuality() test 3: verify low value reverts to zero", harvey.getQualityValue( QUAL_STRENGTH ), 0.0f );

// Conclude outM.close(); System.out.println( "\nMethod tests of EncounterCharacter class concluded." ); }

Listing

page 10

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

/ Class to test repainting of characters. Creates a window, which will contain

  • several copies of the character image. / private static class testCharacterImage extends Frame {*

/ Instance attribute that remembers which character image to display. / private EncounterCharacter characterI;*

/ Basic constructor -- create a window for testing some character's image.

  • @param characterP Character whose image is to be tested. / testCharacterImage(EncounterCharacter characterP) { super(characterP.getName()); // Do all normal Frame initialization. characterI = characterP; // Remember which character we're testing. }*

Listing page 11

Adapted fromAdapted fromAdapted fromAdapted fromAdapted fromAdapted from Software Engineering: An Object-Oriented Perspective Software Engineering: An Object-Oriented Perspective Software Engineering: An Object-Oriented Perspective Software Engineering: An Object-Oriented Perspective Software Engineering: An Object-Oriented Perspective Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 20001), with permission. by Eric J. Braude (Wiley 20001), with permission.by Eric J. Braude (Wiley 20001), with permission.by Eric J. Braude (Wiley 20001), with permission.by Eric J. Braude (Wiley 20001), with permission.by Eric J. Braude (Wiley 2001), with permission.

/ Repaint the display areaof the frame.

  • @param drawP Graphics context for drawing the character. / public void paint(Graphics drawP) { Dimension frameSizeM = getSize(); // Size of the window area. int widthUnitM = frameSizeM.width / 5; // Convenient divisions of window. int heightUnitM = frameSizeM.height / 5;*

characterI.showCharacter(this, drawP, // Drawn small, facing right. new Point(widthUnitM, heightUnitM), heightUnitM, false);

characterI.showCharacter(this, drawP, // Drawn large, facing left. new Point(widthUnitM4, heightUnitM3), heightUnitM2, true);*

characterI.showCharacter(this, drawP, // Drawn large, facing right. new Point(widthUnitM2, heightUnitM2), heightUnitM2, false);*

characterI.showCharacter(this, drawP, // Drawn small, facing left. new Point(widthUnitM3, heightUnitM4), heightUnitM, true); }**

} // End of testCharacterImage inner class

Listing page 12

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

public static boolean checkAssertion ( int loopSoFarP, int indexOfMaxP, double[] arrayP ) { // First establish following booleans:

boolean b1M = true; / means values of arrayP[ ] are lower than arrayP[ indexOfMaxP ] for all indices < indexOfMaxP / if( indexOfMaxP != 0 ) // b1M true if max so far is first element for( int u = 0; u < indexOfMaxP; ++u ) b1M &= ( arrayP[u] < arrayP[ indexOfMaxP ] );

....

Assertion-based testing for max() 1/

public static boolean checkAssertion

( int loopSoFarP, int indexOfMaxP, double[] arrayP )

{

// First establish following booleans:

boolean b1M = true; / means values of arrayP[ ] are lower than arrayP[ indexOfMaxP ] for all indices < indexOfMaxP / if( indexOfMaxP != 0 ) // b1M true if max so far is first element for( int u = 0; u < indexOfMaxP; ++u ) b1M &= ( arrayP[u] < arrayP[ indexOfMaxP ] );

boolean b2M = true; / means vals. of arrayP[ ] no higher*

than arrayP[ indexOfMaxP ] for indices

*indexOfMaxP … loopSoFarP / for( int v = indexOfMaxP; v <= loopSoFarP; ++v ) b2M &= ( arrayP[v] <= arrayP[ indexOfMaxP ] );

Assertion-based

Testing for Defining an max() Assertion Checker: 1 of 2:

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

if ( // Loop has progressed up to index loopSoFarP ( 0 <= loopSoFarP ) && (loopSoFarP < arrayP.length ) && // indexOfMaxP is the index <= loopSoFarP ... ( 0 <= indexOfMaxP ) && ( indexOfMaxP <= loopSoFarP ) && b1M && b2M // ... where the first max occurs ) { System.out.println( "Assertion valid" ); return true; } else { System.out.println( "Assertion invalid" ); return false; } }

Defining an Assertion Checker for max(): 2 of 2

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Paths to be Checked

Parameter & settings make sense?

Parameter name too long?

N

N Y

Decision

Coverag

e

Set _name to “defaultName"

Y

Truncate name

Set _name to parameter

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Coverage example

  • It’s hard to generate test

cases that meet coverage

criteria

  • Statement coverage
    • 7 stmts; 1 case
    • x>k => one case
  • Branch testing
    • 4 branches; 2 cases
    • x>k & res>
    • x <=k & res <= 0
  • Path testing
    • 1 case for each of 4 paths

x>k?

x++

res=f(x, ptr)

res>0?

ptr=true

print(res)

ptr=false

Perform Method Testing (Humphrey)

  1. Verify operation at normal parameter values (a black box test based on the unit’s requirements)
  2. Verify operation at limit parameter values

(black box)

  1. Verify operation outside parameter values

(black box)

  1. Ensure that all instructions execute

(statement coverage)

  1. Check all paths, including both sides of all branches (decision coverage)
  2. Check the use of all called objects
  3. Verify the handling of all data structures
  4. Verify the handling of all files

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Perform Method Testing (Humphrey

  1. Check normal termination of all loops

(part of a correctness proof)

  1. Check abnormal termination of all loops
  2. Check normal termination of all recursions
  3. Check abnormal termination of all recursions
  4. Verify the handling of all error conditions
  5. Check timing and synchronization
  6. Verify all hardware dependencies

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Relating Tests to Requirements & Design

(1) D-Requirements

3.2.EC.1.2 Qualities of Encounter characters

Every game character has the same set of qualities. Each quality shall be a non- negative floating point number with at least one decimal of precision....

(2) Design GameCharacter Requirements

An abstract class with attribute name ...

....

Relating Tests to

Requirements &

(1) D-Requirements

3.2.EC.1.2 Qualities of Encounter characters

Every game character has the same set of qualities. Each quality shall be a non- negative floating point number with at least one decimal of precision....

Characters

GameCharacter

EncounterCharacter adjustQuality()

(2) Design GameCharacter Requirements

An abstract class with attribute name ...

Encounter Characters ... against this requirement

Test this method ...

Test this class ...

... against this requirement

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Unit test

Applied to ...

Concentration Stamina

Results in a zero

value?

1. Within range

No:

Test 1.

Test 1.1.

etc.

Yes:

Test 1.

Test 1.2.

etc.

Partitioning of

Range for Unit

Testing 1 of 2 Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Unit test

Applied to ...

Concentration Stamina

Results in a zero

value?

2. Outside range

No:

Test 2.

Test 2.1.

etc.

Yes:

Test 2.

Test 2.2.

etc.

Partitioning of

Range for Unit

Testing 2 of 2 Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Agenda

  • Testing: Definitions and objectives
  • Black-box test case generation for units of

code

  • Running test cases: scaffolding
  • Clear-box/White-box/Glass-box testing

guidelines

  • Planning testing
    • When can/should you stop testing?

Plan for Unit Testing

1. Decide on the philosophy for unit testing - individual engineer responsible (common)? - reviewed by others? - **designed & performed by others?

  1. Decide what / where / how to document**
    • individual’s personal document set (common)?
    • how / when to incorporate into other types of testing?
    • incorporate in formal documents?
    • **use tools / test utilities?
  2. Determine extent of unit testing (i.e., in advance).**
    • do not just “test until time expires”
    • **prioritize, so that important tests definitely performed
  3. Decide how and where to get the test input**
    • **see section tbd.
  4. Estimate the resources required**
    • **use historical data if available
  5. Arrange to track time, defect count, type & source**

Adapted from Software Engineering: An Object-Oriented Perspective by Eric J. Braude (Wiley 2001), with permission.

Quality of test cases

  • Error density is not usually constant
    • Pareto (80/20) rule
      • 80% defects originate in 20% of units/places in a unit
  • Most errors are local
    • Reqts. & design errors are disproportiately expensive

because of delocalized effects in code

  • But most programming errors require changes to one unit
  • Typical defect rates (Microsoft applications)
  • 10-20 defects/KLOC during unit testing
  • 0.5 defects/KLOC after release

Mutation testing

n How does a manager measure the adequacy of the test cases?

  • E.g. to decide when to release? n (1) Track error detection and release when below a threshold

n (2) Mutation testing

  • Deliberately introduce bugs
  • Measure how many of those bugs are found
  • Use statistical reasoning to predict how many other bugs remain

in the code

  • Assumptions:

t Injected bugs and residual bugs are similar

t Bugs are equivalent in effect