Mini-project 4: Unit Testing
Instructions
The purpose of this mini-project is to give you practice with creating and running unit tests in Java applications.
Create a module called MP4. In MP4, create a new directory called "test": right click on the MP4 module in the Project (not Package) tool window to the left, select "New" → "Directory"). Now right click that directory and select "Mark Directory As" → "Test Source Root".
Create a class called NumberOps
with the following structure:
NumberOps |
---|
-curValue : int |
+setValue( value : int ) |
+getValue() : int |
+isOdd() : boolean |
+isDivisibleBy( int : value ) : boolean |
Create test cases for this class in IntelliJ by clicking the class name and wait a few seconds; a light bulb should appear to the left. Click on it and select "Create Test". In the window that pops up, select JUnit4 at the top and click the "Fix" button that appears just below it. Keep the default class name (NumberOpsTest). Check the "setUp/@Before" option. Also check off all of the methods listed at the bottom. Select "OK".
At the top of NumberOpsTest
, add
import static org.hamcrest.CoreMatchers.*;
—that'll let you
use is()
among other matchers.
Fill in each of the methods in the resulting NumberOpsTest
class. The setUp
method should just create an instance
of the NumberOps
class and store it in a private data member.
The other methods should each test their corresponding method in the
NumberOps
class. Be sure to cover more than one case for each.
Run the tests by right-clicking in the NumberOpsTest
class and
clicking "Run NumberOpsTest with Coverage".
If all is well, you should see that 4 of 4 tests passed.
Now add a bug to the NumberOps
class: make the isOdd
method return false when the current value is odd, and true otherwise (e.g.,
the exact opposite of the expected behavior). Re-run the tests. You should get
and error and specifically, it should tell you which test method caused the
error.
Submission
Create a JAR file for MP4. See this page for the rubric. See the Canvas page to upload your submission.
(Back to top)