Professional Documents
Culture Documents
Writing Methods Running Unit Tests: CS 1301 - Computer Science I
Writing Methods Running Unit Tests: CS 1301 - Computer Science I
◦ Next time:
◦ Exceptions, review of preconditions
◦ JUnit tests with Exceptions
◦ Activity 05
◦ Lab 05 goes out
Write 3 examples:
Testing the parameterized
constructor
TESTING
Testing Terminology
◦ Bug – an error in the code
◦ Debugging – the process of localizing and correcting bugs in
code
◦ Testing – the process of checking that a program is correct
Create
[test Write Run [no]
New fails] Tests Pass? Debug
Code Tests
Test
[yes]
Testing Terminology
● test: program code whose single responsibility is to
make sure other program code works correctly
○ unit testing is a best practice for software developers
Unit Test
◦ Test the smallest unit of code feasible in a specific use case
Test Suite
◦ Collection of unit tests.
Assertion
◦ Common testing construct (not just Unit Testing)
◦ Condition that is asserted to always be true
◦ Generates an error when the condition fails
◦ Typically provide a descriptive error message
Interpreting a Passing Test
● Remember,
“set of small tests to collectively test the
system”
WRITING
METHODS WITH
PARAMETERS
Setter
A setter is a simple method that sets the value of a field.
/**
* Sets the person's age
*
* @precondition age >= 0
* @postcondition getAge() == age
*
* @param age @param: describes the parameter
* the person's new age required for all parameters
*/
public void setAge(int age) {
this.age = age; body: stores the value in the
} setter's parameter into the field
associated with the setter
Mutator Method
Method that alters the value stored in a field
/**
* Ages the Person by the given number of years.
*
* @precondition years >= 0
* @postcondition getAge() == getAge()@prev + years
*
* @param years
* the number of years to age by
*/
public void growOlderBy(int years) {
this.age = this.age + years;
}
Testing growOlderBy()
Test
Code
● named changeName
● with two parameters:
○ firstName
○ lastName
● that changes the Person's name based on the parameters’
values
● don’t forget about pre- and postconditions
/**
* Gets the person's last name
*
* @return the person's last name
*/
public String getLastName() {
return this.lastName;
}
/**
* Gets the person's first name
*
* @return the person's first name
*/
public String getFirstName() {
return this.firstName;
}
Example: method that
calculates and returns a value
/**
* Gets the person's initials, as a String.
*
* @return the person's initials, as a String.
*/
public String getInitials() {
}
Practice writing a method
with a return value
In the Eclipse project on Moodle:
}
Practice writing a method
with parameters and return
In the Person class, write a method:
◦ Name the method getFormalName
Example:
◦ If the title is "Dr." and the Person's full name is ”Doogie Howser", then
this method will return "Dr. Howser”
◦ Uncomment the tests in TestGetFormalName and ensure they pass.