测试数组是否为空JUNIT

时间:2017-04-01 17:46:26

标签: java arrays junit

我想写一个显示游戏牌组的方法。 我用98个元素

初始化了private int [] cards = new int[98];
public int[] getCards() {
    return cards;
}

我还创建了一个get和set方法

public void setCards(final int... cards) {
    this.cards = cards;
}

drawCard

我写的方法叫做Array。如果我使用这种方法,它应该删除public int drawCard() throws IndexOutOfBoundsException { if (getCards().length == 0) { throw new IndexOutOfBoundsException("No Cards Left!"); } setCards(ArrayUtils.removeElement(getCards(), 0)); return getCards()[0]; } 中的第一个元素并将其返回。

== 0

然后我写了JUnit测试。 测试应该删除所有98个元素,然后数组应为空@Test public void testDrawCard() { Deck deck = new Deck(); assertThat(deck.getCards().length).isEqualTo(98); for(int x = 98; x >= 0; x--){ deck.drawCard(); } assertThat(deck.getCards().length).isEqualTo(0); } 。 但测试总是停在1。

java.lang.ArrayIndexOutOfBoundsException: 0
at edu.hm.hafner.java2.thegame.Deck.drawCard(Deck.java:35) 

错误讯息:

at edu.hm.hafner.java2.thegame.DeckTest.testDrawCard(DeckTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  

35 =返回行

import json
import os.path

def InputFile():
    global compfilename
    compfilename = input("Please enter an existing compressed file to be decompressed: ")

def Validation2():
    if compfilename == (""):
        print ("Nothing was entered for the filename. Please re-enter a valid filename.")
        Error()
    if os.path.exists(compfilename + ".txt") == False:
        print ("No such file exists. Please enter a valid existing file.")
        Error()

def OutputDecompressed():
    global words
    global orgsentence
    newfile = open((compfilename)+'.txt', 'r')
    saveddata = json.load(newfile)
    orgsentence = saveddata
    words = orgsentence.split(' ')
    print ("Words in the sentence: " + str(words))

def Uniquewords():
    for i in range(len(words)):
        if words[i] not in unilist:
            unilist.append(words[i])
    print ("Unique words: " + str(unilist))

def PosText():
    global pos
    find = dict((sentence, words.index(sentence)+1) for sentence in list(words))
    pos = (list(map(lambda sentence: find [sentence], words)))
    return (pos)

def Error():
    MainCompression()

def OutputDecompressed2():
    for number in pos:
    decompression.append(orgsentence[int(number)-1])
    finalsentence = (" ".join(decompression))
    print ("Original sentence from file: " + finalsentence)

def OutputText():
    print ("The positions of the word(s) in the sentence are: " + str(pos))

def MainCompression():
    global decompression
    decompression = []
    global unilist
    unilist = []
    InputFile()
    Validation2()
    OutputDecompressed()
    Uniquewords()
    PosText()
    OutputText()
    OutputDecompressed2()

MainCompression()

有人知道什么是错的吗?

2 个答案:

答案 0 :(得分:1)

for(int x = 98; x >= 0; x--)

这会在x >= 0时执行循环。也就是说,如果我们递减x并且它得到值0,我们再次执行循环,因为0 >= 0为真。然后,我们递减x并发现它为-1,所以循环停止。这意味着循环将执行x = 98,97,96,...,2,1,1。此列表中有99个数字,因此循环执行99次。

由于您根本没有使用x,因此没有理由让它从顶部开始向下移动。如果唯一的目的是确保你的循环执行98次,那么就不要聪明 - 只需使用标准的for循环习语:

for (int i = 0; i < 98; i++)

它对程序的执行没有任何影响。但是,除非必要时坚持使用标准习语,否则你可以节省一些脑细胞,最终可以减少很多错误。

答案 1 :(得分:0)

@ajb是对的,但是当你想要正常迭代时,你会从长度 - 1 开始,因为索引从0开始。所以在你的风格中,循环应该是

for(int x = 98 - 1; x >= 0; x--)

但是,你并没有在循环中使用x变量,所以只要你正在绘制98个元素,顺序就不重要了。