Instructor: Todd Dole
In this lab, we will practice creating unit tests with JUnit, using our MathOperations
class from the previous week's lab. Then, we will add a new method using test driven development principles.
Follow the instructions here to install and configure JUnit 4.
For example, to test MathOperations.addNumbers, you could write a test like this:
@Test public void testAddNumbers() { assertEquals(MathOperations.addNumbers(2,3), 5); // Checks that addNumbers(2,3) returns 5 assertEquals(MathOperations.addNumbers(5, -2), 3); // Checks that addNumbers(5,-2) returns 3 }
Hint: for testing doubles with many digits, you can use Math.round to round off the values for easy comparison.
Now, let's practice test driven development. Remember that the idea is to create a unit test for a new method first (Red), and then write the code so that the test passes (Green).
Paste the following code into your MathOperationsTest.java file:
@Test public void testCelciusToFahrenheit() { assertEquals(MathOperations.celciusToFahrenheit(0), 32); assertEquals(MathOperations.celciusToFahrenheit(100), 212); }
Now, write a celciusToFahrenheit method that will make the test pass! (Hint: the formula is the reverse of the Fahrenheit to Celcius formula we used last week.)
Submit both MathOperations.java
and MathOperationsTest.java
via Canvas by the due date. Make sure you are submitting this week's versions from your Project src folder!