Search code examples
javajunitjunit5

How can I test the value of a static attribute with JUnit?


I have the following Job class:

 public class Job {
    static int jobTotal = 0;

    private int jobNumber;
    private Address location;
    private String description;
    private List<Equipment> requiredEquipment;
    private Date plannedDate;

    public static int getJobTotal() {
        return jobTotal;
    }
 }

This class contains a bunch of other methods, but getJobTotal is the only one that is relevant in this case.

Inside JobTest.java I run a couple of tests for each of these methods (there are around 14 test methods):

class JobTest {
    Job j1;

    @BeforeEach
    void init() {
        Address a = new Address("street", 111, "zip", "city");
        ArrayList<Equipment> equipment = new ArrayList<>();
        equipment.add(new Torch("Don't turn on or it explodes"));
        j1 = new Job(a, "Replace lightbulb", equipment, new Date(15, 10, 2023));
    }

    @Test
    void testConstructor() {
        assertFalse(j1 == null);
    }

    @Test
    void getJobTotal() {
        //? How do I test for getJobTotal?
    }
}

However, tests are not ran in the order in which they are defined inside the test file. As a result, my BeforeEach could trigger an unknown amount of times before reaching getJobTotal(the test method I mean).

How could I test that the getter returns a "correct" value? Because I can't really place any value inside the "expected" parameter of assertEquals().

PS: I am using JUnit 5


Solution

  • To test the value of a static attribute like jobTotal in your Job class using JUnit 5, you can use the @BeforeAll and @AfterAll annotations to set and reset the value. These annotations are used for setup and cleanup methods that run once before and after all the test methods in a test class. Here's how you can do it.

    @BeforeEach
    void init() {
        Address a = new Address("street", 111, "zip", "city");
        ArrayList<Equipment> equipment = new ArrayList<>();
        equipment.add(new Torch("Don't turn on or it explodes"));
        j1 = new Job(a, "Replace lightbulb", equipment, new Date(15, 10, 2023));
    }
    
    @Test
    void testConstructor() {
        assertFalse(j1 == null);
    }
    
    @Test
    void testGetJobTotal() {
        // Assuming you have set up some jobs, you can test the static attribute like this:
        int initialTotal = Job.getJobTotal();
        
        // Perform actions that change the jobTotal, e.g., creating more jobs
    
        int updatedTotal = Job.getJobTotal();
    
        // Now you can assert the values
        assertEquals(initialTotal + 1, updatedTotal); // Or any expected value based on your test scenario
    }
    
    @BeforeAll
    static void setup() {
        // Initialize or set up anything needed before running the tests
    }
    
    @AfterAll
    static void cleanup() {
        // Clean up or reset any state that was changed during testing
    }
    

    }