JUnit test if else case

落爺英雄遲暮 提交于 2019-12-14 03:59:16

问题


How to write test to current method? I use jUnit 4.

   public void setImage() {
        if(conditionOne){
            myView.setImageOne();
        } else {
            myView.setImageTwo();
        }
    }

回答1:


You need to write two tests to cover both the scenarios as below:

import org.junit.Test;

public class SetImageTest {

    @Test
    public void testSetImageForConditionOne() {
        //write test to make conditionOne true
    }

    @Test
    public void testSetImageForElseCondition() {
        //write test to make conditionOne false
    }
}



回答2:


Okay... there is a flaw in the way you wrote this method. There is something called testable code. Here is a link (how to write testable code and why it matters) that discusses testable code.

The method you wrote above is non-deterministic. Which means the method can exhibit different behaviors on different runs, even if it has the same input. In your case you have no input.

Currently, your original method is based on the environment of the method and not the input. This practice can make it very difficult and in some cases impossible to write proper test for your code.

So this is how you want it to look like...

  public void setImage(boolean conditionOne) {
    if(conditionOne){
        myView.setImageOne();
    } else {
        myView.setImageTwo();
    }
}

Now that the test is deterministic your either going to have to test the variables that are in the environment, or have a return statement.

So (adding a return statement) you can do this.

  public static void setImage(boolean conditionOne, type myView) {
    if(conditionOne){
        myView.setImageOne();
    } else {
        myView.setImageTwo();
    }
    return myView; 
  }

Now your test can look something like this

public class SetImageTest {
  @Test
  public void testSetImage() {
    type myViewOrig;
    //define myViewOrig
    type myView1;
    //define myView1
    type myView2;
    //define myView2

    assertEquals(setImage(<true>, type myViewOrig), myView1);
    assertEquals(setImage(<false>, type myViewOrig), myView2);
  }
}

Or you can just test the myView object after running your setImage method.



来源:https://stackoverflow.com/questions/40278040/junit-test-if-else-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!