Java 如何覆盖此方法上的所有分支?

Java 如何覆盖此方法上的所有分支?,java,testing,junit,Java,Testing,Junit,我不明白如何完全测试这个方法。Eclipse写到“遗漏了4个分支中的2个” public boolean hasNext(){ 返回currenindex

我不明白如何完全测试这个方法。Eclipse写到“遗漏了4个分支中的2个”

public boolean hasNext(){
返回currenindex
下面是我编写的单元测试

@Test
public void hasNextIteratorTest() throws FileNotFoundException {
    Part4 p = new Part4();

    Iterator<String> it = p.iterator();
    p.add("hello");
    p.add("dear");
    p.add("friend");
    p.add("!");
    while (it.hasNext()) {
        it.remove();
    }
}
@测试
public void hasNextIteratorTest()引发FileNotFoundException{
第4部分p=新的第4部分();
迭代器it=p.Iterator();
p、 加上(“你好”);
p、 加上(“亲爱的”);
p、 加上(“朋友”);
p、 加上“!”;
while(it.hasNext()){
it.remove();
}
}

如果要覆盖所有分支,必须测试调用方法时可能发生的所有条件

//1. 
currIndex < currentSize && aList[currIndex] != null;
//2.
currIndex > currentSize && aList[currIndex] != null;
//3.
currIndex < currentSize && aList[currIndex] == null;
//4.
currIndex > currentSize && aList[currIndex] == null;
//1。
currIndexcurrentSize&&List[currIndex]!=无效的
//3.
currIndexcurrentSize&&List[currIndex]==null;

您必须在@Test方法(或多个方法)中强制执行此结果。

最好的建议是添加具有明显名称的不同测试用例,每个测试用例单独执行。另外,由于它们的示例代码中没有包含断言示例,因此添加断言示例将非常有用?按原样,它将涵盖“索引<大小和项目不为空”和“索引>=大小和项目不为空”。因此,您必须强制项为null的分支。所有这些分支都应该有自己的测试,您应该使用断言来提供有用的消息。你应该隔离要测试的项目。意思:您想测试
hasNext
,在某些条件下它应该返回true或false。因此,您必须创建这些条件,然后调用该方法并根据预期结果检查结果。提示:如果您不理解代码中的所有分支。。。把它们说清楚。因此,如果您有
返回A&&B
。。。您可以首先将其转换为
boolean A=。。;布尔B=;返回A&B
//1. 
currIndex < currentSize && aList[currIndex] != null;
//2.
currIndex > currentSize && aList[currIndex] != null;
//3.
currIndex < currentSize && aList[currIndex] == null;
//4.
currIndex > currentSize && aList[currIndex] == null;