📋
Auto-Grading for Teachers
  • Learn How to Auto-Grade
  • Assertions and Unit Testing
  • Request / Submit Examples
  • 🐍Python Examples
    • Check Variable Values
    • Output Tests
    • Input / Output Tests
    • Print Function Tests
    • Return Function Tests
    • Random Number Tests
    • Parse Student Code
  • ☕Java Examples
    • Check Variable Values
    • Output Tests
    • Input / Output Tests
    • Return Method Tests
    • Class - .toString() and Void Method Tests
    • Random Numbers Tests
    • Array and ArrayList Tests
    • Parse Student Code
  • 💎Ruby Examples
    • Output Tests
    • Input / Output Tests
    • Print Function Tests
    • Return Function Tests
    • Parse Student Code
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Java Examples

Check Variable Values

Checking variable values can be a bit tricky in Java. For example, it can be hard to check the following variable values.

class Example 
{
    public static void main(String[] args) 
    {
        String firstName = "Bob";
        String lastName = "Jones";
        System.out.println(firstName);
        System.out.println(lastName);
    }
}

This is because firstName and lastName are local to the main() method and created when it is executed and destroyed when it is done.

We can prevent this by declaring these variables as static outside the main() method.

class Example
{
    static String firstName;
    static String lastName;
 
    public static void main(String[] args)
    {
        firstName = "Bob";
        lastName = "Jones";
        System.out.println(firstName);
        System.out.println(lastName);
    }
}

We typically do not teach students to declare variables this way (most curriculums do not) so you may need to tweak your curriculum to auto-grade early assignments that teacher variable assignment and console output.

The grading test involves calling the main method (where you expect the variables to be assigned values and checking that each variable equals the expected value.

import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.*;

public class CodingRoomsUnitTests {

    @Test
    public void testDefaultCase() {
        Example.main(null);
        assertEquals(Example.firstName, "Bob");
        assertEquals(Example.lastName, "Jones");
    }
}

PreviousParse Student CodeNextOutput Tests

Last updated 3 years ago

Was this helpful?

☕