如何使用JUnit测试静态属性的值?[副本]

frebpwbc  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(124)

此问题已在此处有答案

How to write a unit test for static variable?(3个答案)
4天前关闭。
我有以下作业类:

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;
    }
 }

这个类包含一堆其他方法,但getJobTotal是唯一与此相关的方法。
在JobTest.java中,我为每种方法运行了几个测试(大约有14个测试方法):

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?
    }
}

但是,测试不会按照测试文件中定义的顺序运行。因此,我的BeforeEach在到达getJobTotal(我指的测试方法)之前可能会触发未知的次数。
如何测试getter返回的值是否“正确”?因为我不能在assertEquals()的“expected”参数中放置任何值。
PS:我用的是JUnit 5

2jcobegt

2jcobegt1#

要使用JUnit 5测试Job类中的静态属性(如jobTotal)的值,可以使用@BeforeAll和@AfterAll注解来设置和重置该值。这些注解用于在测试类中的所有测试方法之前和之后运行一次的设置和清理方法。你可以这么做。

@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
}

}

相关问题