Each example assumes the students file name is Example#.java replacing # with the actual example number. You can call the methods based on the student filename of your choice.
Example 1 - Add Five
Students write an int method named addFive(int number) that takes an integer as a parameter and returns an int equal to 5 plus the parameter value.
Grading Tests:
import org.junit.Test;
import static org.junit.Assert.*;
public class CodingRoomsUnitTests {
@Test
public void testDefaultCase() {
// You may rename this method to better suit the purpose of your test case
// Your test case logic here
assertEquals(10, Example1.addFive(5));
assertEquals(5, Example1.addFive(0));
assertEquals(11, Example1.addFive(6));
}
}
Sample Solution:
Example1.java
public class Example1
{
public static int addFive(int number)
{
number += 5;
return number;
}
}
Example 2 - Average
Students write a method that takes 5 int values as parameters and returns the average value of the 5 ints as a double. The method must be named average() and it must have 5 int parameters. The method must return a double.
Example: Calling average(1, 5, 7, 4, 10) would return 5.4.
Note: Assertions with doubles must have delta value (tolerance when comparing values).
Grading Tests:
import org.junit.Test;
import static org.junit.Assert.*;
public class CodingRoomsUnitTests {
@Test
public void testDefaultCase() {
// You may rename this method to better suit the purpose of your test case
// Your test case logic here
assertEquals(5.4, Example2.average(1, 5, 7, 4, 10), 0.001);
assertEquals(9.6, Example2.average(5, 9, 24, 6, 4), 0.001);
}
}
Sample Solution:
Example2.java
public class Example2
{
public static double average(int a, int b, int c, int d, int e)
{
//Calculate sum of 5 numbers
int s = a + b + c + d + e;
//cast s to double and divide by 5
return (double) s / 5;
}
}
Example 3 - Repeats
Students write a method that takes a String parameter. If the String has a double letter (i.e. contains the same letter twice in a row) then it should return true. Otherwise, it should return false.
This method must be named hasRepeat(String str) and have a String parameter. This method must return a boolean.
Grading Tests:
import org.junit.Test;
import static org.junit.Assert.*;
public class CodingRoomsUnitTests {
@Test
public void testDefaultCase() {
// You may rename this method to better suit the purpose of your test case
// Your test case logic here
assertTrue(Example3.hasRepeat("mississippi"));
assertFalse(Example3.hasRepeat("capsized"));
assertTrue(Example3.hasRepeat("mazzone"));
assertFalse(Example3.hasRepeat("this"));
}
}
Sample Solution:
Example3.java
public class Example3
{
public static boolean hasRepeat(String str)
{
for(int i = 0; i < str.length()-1; i++)
{
if(str.substring(i, i+1).equals(str.substring(i+1, i+2)))
{
return true;
}
}
return false;
}
}