我有以下工作类别:
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() 的“预期”参数中放置任何值。
PS:我正在使用 JUnit 5
要使用 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
}
}