Add Numbers

Assignment

Write a class called Calculator with a method public static int add(int x, int y) that returns their sum \(x + y\).

The student submits this as Calculator.java (the file name must match the class name).

Example Solution

public class Calculator {
    public static int add(int x, int y) {
        return x + y;
    }
}

Example Grader

Upload the following JUnit test class as the assignment’s grader. It must be named Grader:

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

// Your grader must be a JUnit test class named `Grader`, uploaded as the
// assignment's grader file. Tin compiles it with the student's `Calculator`
// submission and runs it in the sandbox; the score is the fraction of these
// @Test methods that pass.
public class Grader {

    @Test
    public void case1() {
        assertEquals(3, Calculator.add(1, 2));
    }

    @Test
    public void case2() {
        assertEquals(7, Calculator.add(3, 4));
    }

    @Test
    public void largeNumbers() {
        assertEquals(21345, Calculator.add(1000, 20345));
    }

    @Test
    public void case4() {
        assertEquals(132, Calculator.add(54, 78));
    }

    // "Secret" cases: use assertTrue, NOT assertEquals. On failure assertEquals
    // prints "expected:<X> but was:<Y>" -- which hands the student the answer, so
    // they could just hardcode it. assertTrue only prints "AssertionError", so
    // the expected value stays hidden. Use it for cases you don't want revealed.
    @Test
    public void secretCase1() {
        assertTrue(Calculator.add(120, 80) == 200);
    }

    @Test
    public void secretCase2() {
        assertTrue(Calculator.add(-50, 50) == 0);
    }
}

This grader uses no @Weight annotations, so each of the 6 tests is worth 1 point (the default) - set the assignment’s “Points possible” to 6. To make some checks worth more, add @Weight(n); see the Nth Fibonacci example.

The last two tests are secret cases: they use assertTrue instead of assertEquals on purpose. On failure, assertEquals prints expected:<…> but was:<…> - which hands the student the answer to hardcode - whereas assertTrue prints only AssertionError, keeping the expected value hidden. Reserve assertEquals for cases where revealing the answer is fine.