-1

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?

  • 1
    'How to implement basic if/else in JUnit tests?' - it is unclear what you mean. – Lesiak May 28 '21 at 15:04
  • @Lesiak - i mean how to place conditional test case –  May 28 '21 at 15:06
  • 3
    1. You set the state of `param1` such that one of the branches is executed. This is probably obvious. 2. You might not need mocking at all - if `param1` and `param2` are easy to construct, it may be easier to check `setValueMethod` on real objects. 3. `setValueMethod` is private. You typically don't test private methods. You could test it via public interface. Changing to package-private is acceptable. As the method seems not to depend on object state, changing to static may be acceptable. Another technique is extracting the method to another object (but such a trivial object not worth it) – Lesiak May 28 '21 at 15:18

1 Answers1

1

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));
}
Matthias
  • 7,432
  • 6
  • 55
  • 88
  • 1
    perfect answer :) But mine class is a private class i can't refer to it also –  May 28 '21 at 14:54
  • @AEmilia Oh, I see. _In my opinion_, you should not test a private method. Instead, you should test a public method, which calls this private method. But if you really want to, you could use something like [Powermock](https://stackoverflow.com/q/8799439/344480)? – Matthias May 28 '21 at 15:07