首页 > 解决方案 > JUnits 检查 IF Else 条件

问题描述

代码文件 - 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
}

如何在 JUnits 中实现 if/else?

标签: javajunitmockito

解决方案


您应该考虑编写两个测试。

@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));
}

推荐阅读