Reputation: 111
I am writing junit test cases for my project but i am facing one problem Here is a method that i am using in one of my java class (GraphNodes.java)
public static ArrayList<String> getCSList() {
System.out.println(CSList.size()); // Output : 3
return CSList; // returns 3 elements in list
}
Now here is my test class for Junit
@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);
}
My junit is failing by saying excepted<3> but actual<0> Also i cannot change the static method to only public because it will affect some functionality of the code and since i am new to junit, i am not getting idea how to fix this.so can anyone help me out here Thanks in Advance!!
Upvotes: 1
Views: 1453
Reputation: 417
You need to validate how you populate the object CSList()
during runtime and do exactly the same when you are running the test.
One option is to have a @BeforeEach method
in your test where it will set the values of what you need during the test.
@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);
}
Upvotes: 1
Reputation: 2200
I think you are trying to write an integration test. So you should call the method, that fills the list with your 3 elements, before checking the list size. If all the logic for that is in your main method you should extract it into its own method.
Upvotes: 0