Using JUnit in Eclipse

JUnit is a unit testing framework for Java that helps programmers write and run automated tests. When using JUnit for testing, the programmer typically writes many small tests to automatically check that a program behaves as expected. Often, the programmer will write one or more tests for each method. For the Yahtzee problem in Lab 02, I have written one test for each method. Each test tries some rolls that should cause the tested method to return false, and some rolls that should cause the tested method to return true; the test invokes the method for each roll and checks that the returned value is as expected.

JUnit is integrated into the lab version of Eclipse. Because you already have an implemented set of JUnit tests and skeleton code for the Yahtzee class, you can the tests right away.

First we need to make JUnit available to Eclipse. Select the Project menu and click on Properties.

On the list to the left choose Java Build Path. In the tab selector, choose Libraries. Press the Add Library... button.

Choose JUnit, and press Next >.

Make sure that JUnit 4 is the JUnit library version, and press Finish.

To run the test, right click on the YahtzeeTest.java file in the Project Explorer panel, select Run As, and then select JUnit Test (see image below):

running junit

In the JUnit output panel, you should see the following:

running junit

Notice that all of the tests have a blue x beside them, indicating that the tests have failed. This is not surprising because all of our methods currently return true for any list of dice.

The Failure Trace tells us that the test failed on line 21 of the tester. On line 21 (highlighted in blue) we see that our invocation of Yahtzee.isThreeOfAkind was expected to return false (this is what the assertFalse method checks for), but our method currently returns true.

The Failure Trace also tells us the dice values that were used when the test failed. We see a roll of 6-5-3-1-1 which is clearly not a three-of-a-kind roll.

To proceed, you need to implement the methods in Yahtzee.java so that they are correct. You can run JUnit every time you make a change in your source code; this will help you debug your code. When you have correctly implemented all of the methods and run JUnit you should see the following in the JUnit output console:

running junit

Notice that all of the tests now have a green check mark beside them indicating that the tests have passed.