Issue
Code File - originalFile.java
private setValueMethod(param1, param2) {
if (param1.getIsMale()) { // Its a boolean
param1.setCity(param2);
} else {
param1.setCity(param1.getOtherCity());
}
}
originalFileTest.java
@Test
public void testSetValueMethod() {
// some previous line setting mock value
when(param1.getIsMale()).then ('.... How to do what i have done in real code file...')
// How to implement if/else in JUnit tests
}
How to implement if/else in JUnits?
Solution
You should consider writing two tests.
@Test
public void shouldUseOtherCityOfParam1() {
ClassUnderTest classUnderTest = new ClassUnderTest();
Param1 param1 = mock(Param1.class);
Param2 param2 = mock(Param2.class);
Param2 otherCity = mock(Param2.class);
when(param1.getIsMale()).thenReturn(false);
when(param1.getOtherCity()).thenReturn(otherCity);
classUnderTest.setValueMethod(param1, param2);
verify(param1).setCity(eq(otherCity));
}
@Test
public void shouldUseParam2() {
ClassUnderTest classUnderTest = new ClassUnderTest();
Param1 param1 = mock(Param1.class);
Param2 param2 = mock(Param2.class);
when(param1.getIsMale()).thenReturn(true);
classUnderTest.setValueMethod(param1, param2);
verify(param1).setCity(eq(param2));
}
Answered By - Matthias