Lab: JUnit Testing Pattern
Objective
In this lab you will learn how to organize a JUnit test fixture so that it can be easily reused for different implementations.
Setup
Follow these steps to set up a project for this lab.
- Create a new Eclipse project by copying
ProjectTemplate. Name the new projectJUnitTestingRevisited. - Create a new JUnit test fixture by following these steps:
- Right-click on the
testfolder in your project and select New > Class; name the classStackTestand click Finish. - Follow the link to
StackTest.java, select all the code on that page (click and hold the left mouse button at the start of the program and drag the mouse to the end of the program) and copy it to the clipboard (right-click the mouse on the selection and choose Copy from the contextual pop-up menu), then come back to this page and continue with these instructions. - Open the
StackTest.javafile; select all the code in the editor, right-click on it and select Paste from the contextual pop-up menu to replace the existing code with the code you copied in the previous step. Save your file.
- Right-click on the
- Repeat the steps above to create another class in the
testfolder, name itStack1LTest, and replace its contents with the code fromStack1LTest.java
Method
- Take a look at the two classes provided and make sure you understand how they are organized.
- Complete the body of the
createFromArgsTestandcreateFromArgsRefmethods inStackTest.javaso that they satisfy their contracts, and the body of theconstructorTestandconstructorRefmethods inStack1LTest.javaso that they instantiate and return stacks of typeStack1Land of typeStack3, respectively. Note that the varargs argument tocreateFromArgscan be interpreted and accessed as an array (guaranteed not to be null). - Run the
Stack1LTestJUnit test fixture and make sure that all test cases complete successfully. If any of the test cases result in failures or errors, that probably indicates a problem with your code for the methods you implemented. - Once everything works as expected, create a new class in the
testfolder, by copying and pastingStack1LTest, and name itStack2Test. Update theconstructorTestmethod so that it instantiates and returns a stack of typeStack2(you can keepStack3as the reference implementation). Run theStack2TestJUnit test fixture and make sure that all test cases complete successfully. This shows how simple it is to reuse theStackTestfixture to test a different implementation ofStack. - Consider the first section of test cases in
StackTest, where we provided a few examples of test cases for theStackkernel methods. Add new test cases to this section ofStackTestto test thoroughly and systematically the kernel methods push, pop, and length. Run the test fixtures and make sure all your test cases succeed.