问题
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