For our first Java Unit project tests we will start with the Stack data structure. Here is the code we used:
Stack.java
public class Stack {
private int maxSize;
private long[] stackArray;
private int top;
public Stack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;
}
public long pop() {
return stackArray[top--];
}
public long peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
}
As you can see above, there is no main method. We will use a unit test case to grade this java file.
Sample test cases:
Testing the constructor:
Stack s = new Stack(10);
return (s.isEmpty());
Testing push():
Stack s = new Stack(10);
s.push(10);
s.push(1);
return (!s.isEmpty());
Testing retrieving values from the Stack via pop():
Stack s = new Stack(10);
s.push(10);
s.push(1);
long num = s.pop();
return (num==1);
The unit test case makes it very simple to quickly write up a wide variety of tests for an object or data structure.
Remember that every single execution path needs a return statement or your test case will error out!
You do this by having a single return with a statement that could return a true or false, as seen below:
int x = 1;
int y = 2;
return (x==y);
OR you can have an if block that returns true/false and an else that also returns, or just a return outside of the if block:
int x = 1;
int y = 2;
if (x==y){
return false;
}
return true;
//or
if (x==y){
return false;
}
else{
return true;
}
Imports
Mimir Classroom is able to handle imports in unit tests. These could include anything, but common imports are ArrayList, Random, etc. It's actually quite easy to add in other modules:
import java.util.Random;
long seed = 1024;
Random rand = new Random(seed);
int randomNumber = rand.nextInt(20);
return (19 >= randomNumber) && (randomNumber >= 0); // make sure the number is between 0 and 19 inclusive
Keep in mind that any imports are test case level, not project level, so they will only be included in the test case you have them included in. Also, the import lines should only appear at the top, above all actual test case code.