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.

import org.junit.Test;
import static org.junit.Assert.*;
import java.nio.file.*;

public class CodingRoomsUnitTests {

    @Test
    public void testDefaultCase() throws Exception {
        int count = 0;
        String student_code = new String(Files.readAllBytes(Paths.get("Example.java")));
        String[] words = student_code.split(" ");

        for (int i = 0; i < words.length; i++) {
            if (words[i].indexOf("System.out.println(") >= 0) {
                count++;
            }
        }
        assertTrue(count >= 2);
    }
}

Last updated