在测试 class(Junit) 中调用静态方法
Calling static method in test class(Junit)
我正在为我的项目编写 junit 测试用例,但我遇到了一个问题
这是我在 java class (GraphNodes.java)
中使用的一种方法
public static ArrayList<String> getCSList() {
System.out.println(CSList.size()); // Output : 3
return CSList; // returns 3 elements in list
}
现在这是我对 Junit
的测试 class
@Test
public void checkCSListCount(){
int actual= GraphNodes.getCSList().size(); // My exceptation here is 3 but in console it shows 0
int excepted = 3;
assertEquals(excepted,actual);
}
我的 junit 失败了,说 excepted<3> 但实际 <0>
此外,我不能将静态方法更改为仅 public,因为它会影响代码的某些功能,而且由于我是 junit 的新手,我不知道如何修复 this.so 谁能帮我解决这个问题
提前致谢!!
我认为您正在尝试编写集成测试。因此,在检查列表大小之前,您应该调用用 3 个元素填充列表的方法。如果所有的逻辑都在你的主要方法中,你应该将它提取到它自己的方法中。
您需要验证在运行时如何填充对象 CSList()
并在 运行 测试时执行完全相同的操作。
一个选择是在你的测试中有一个@BeforeEach method
,它会在测试期间设置你需要的值。
@BeforeEach
public void setUp() {
GraphNodes.setCSList(Arrays.asList("A","B","C"));
}
@Test
public void checkCSListCount(){
int actual= GraphNodes.getCSList().size();
int excepted = 3;
assertEquals(excepted,actual);
}
我正在为我的项目编写 junit 测试用例,但我遇到了一个问题 这是我在 java class (GraphNodes.java)
中使用的一种方法 public static ArrayList<String> getCSList() {
System.out.println(CSList.size()); // Output : 3
return CSList; // returns 3 elements in list
}
现在这是我对 Junit
的测试 class@Test
public void checkCSListCount(){
int actual= GraphNodes.getCSList().size(); // My exceptation here is 3 but in console it shows 0
int excepted = 3;
assertEquals(excepted,actual);
}
我的 junit 失败了,说 excepted<3> 但实际 <0> 此外,我不能将静态方法更改为仅 public,因为它会影响代码的某些功能,而且由于我是 junit 的新手,我不知道如何修复 this.so 谁能帮我解决这个问题 提前致谢!!
我认为您正在尝试编写集成测试。因此,在检查列表大小之前,您应该调用用 3 个元素填充列表的方法。如果所有的逻辑都在你的主要方法中,你应该将它提取到它自己的方法中。
您需要验证在运行时如何填充对象 CSList()
并在 运行 测试时执行完全相同的操作。
一个选择是在你的测试中有一个@BeforeEach method
,它会在测试期间设置你需要的值。
@BeforeEach
public void setUp() {
GraphNodes.setCSList(Arrays.asList("A","B","C"));
}
@Test
public void checkCSListCount(){
int actual= GraphNodes.getCSList().size();
int excepted = 3;
assertEquals(excepted,actual);
}