Parse Student Code
Often you just want to make sure students successfully used a particular function/command/structure. The simplest way I have found to do this is just parse the student's code file and make sure what you are looking for is there.
For example, maybe you want to make sure the student used println() at least 2 times. We can parse the student's code file and count how many times "System.out.println(" is present in their code.
This test assumes the student's file name is Example.java.
1
import org.junit.Test;
2
import static org.junit.Assert.*;
3
import java.nio.file.*;
4
​
5
public class CodingRoomsUnitTests {
6
​
7
@Test
8
public void testDefaultCase() throws Exception {
9
int count = 0;
10
String student_code = new String(Files.readAllBytes(Paths.get("Example.java")));
11
String[] words = student_code.split(" ");
12
​
13
for (int i = 0; i < words.length; i++) {
14
if (words[i].indexOf("System.out.println(") >= 0) {
15
count++;
16
}
17
}
18
assertTrue(count >= 2);
19
}
20
}
Copied!
Last modified 1mo ago
Export as PDF
Copy link