java JUnit 测试 if else case
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40278040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JUnit test if else case
提问by IntoTheDeep
How to write test to current method? I use jUnit 4.
如何将测试写入当前方法?我使用 jUnit 4。
public void setImage() {
if(conditionOne){
myView.setImageOne();
} else {
myView.setImageTwo();
}
}
回答by developer
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
}
}
回答by Rohan D'Souza
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.
既然测试是确定性的,您要么必须测试环境中的变量,要么有一个 return 语句。
So (adding a return statement) you can do this.
所以(添加一个 return 语句)你可以这样做。
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.
或者您可以在运行 setImage 方法后测试 myView 对象。