1
SWEN221: Software Development
#2 – Testing I
David J. Pearce & Marco ServettoComputer Science, Victoria University
2
Testing
Why Test?
4
Software Testing
• Why test?– Code never works first time!– You must test it to find the bugs!– But, what is a bug?
• Obvious ones e.g. divide-by-zero• Subtle failures to meet specification
– Testing only increases confidence in software• It cannot guarantee there are no bugs
Specification ProgramCodeDevelopment
Testing
5
Testing
Edsger Wybe Dijkstra:
“Program testing can be used to show the presence of bugs, but never to show their absence!”
http://www.cs.utexas.edu/users/EWD/
6
What testing cannot do• Unfortunately, testing cannot be exhaustive
– Has 232 possible inputs. – If each test takes 1 second then exhaustive test takes:
– Must pick out test cases to represent input domain
boolean isPrime(int x) {…}
8
Unit testing with JUnit
JUnit a Unit Testing Framework– Kent Beck (XP, Smalltalk)– Erich Gamma (Eclipse, Patterns)
Using Junit:– Tests are Java methods– Test suites are Java classes– Annotations mark them out– API for writing tests– IDE support (Eclipse…)
• http://junit.sourceforge.net/
9
Anatomy of a JUnit Test
In your test class– (typically 1-1 with application classes)
import static org.junit.jupiter.api.Assertions.*;import org.junit.jupiter.api.Test;
• Annotate methods with @Test
10
The JUnit API
A range of assertion methods:• assertTrue(boolean)• assertTrue(String message, boolean)
And a whole lot more:• assertEquals(Object expect, Object actual)• assertEquals(float expected, float actual, float delta)• assertNull, assertNotNull• assertTrue, assertFalse• assertSame, assertNotSame• fail(), fail(String message)
public class MyDate {private int day, month, year; // 1 <= day <= 31 and 1 <= month <= 12
public MyDate(int day, int month, int year) {this.day = day;this.month = month;this.year = year;
// check invariantS holdif(day <= 0 || month < 0) { throw new RuntimeException(…); }
else if((month==4 || month==6 || month==9 || month==11) && day > 30) {throw new RuntimeException("Cannot construct invalid Date!");
} else if(month == 2 && (day>29 || (day>28 && !(year%4==0 &&(year%100 != 0 || year%400==0))))) {
throw new RuntimeException("Cannot construct invalid Date!");
} else if(day > 31 || month > 12) {throw new RuntimeException("Cannot construct invalid Date!"); }
}
public int day() { return day; }public int month() { return month; }public int year() { return year; }}
12
Starting JUnit
13
A simple JUnit testpublic class MyDateTest {@Test public void testConstructValidDate() {
MyDate d; // all these dates are right!d = new MyDate(1,1,1);d = new MyDate(1,05,2006);d = new MyDate(28,02,2006);d = new MyDate(29,02,2008);d = new MyDate(31,05,2008);
}}
14
Testing the Happy Path
15
Testing the Happy Path
16
Testing the Unhappy Path
17
Why?
Top Related