簡體   English   中英

遞歸 JUnit 測試

[英]Recursive JUnit Test

因此,我正在嘗試編寫 3 個測試用例來查找我編寫的遞歸方法是否正確。 我對 JUnit 不太好,但這就是我到目前為止所得到的。

如何證明我的遞歸方法在 JUnit 中是正確的(如果是)?

這是我的班級:

public class Rhino {
    private String co; //The country in which this Rhino was born. Not null
    private Rhino parent; //null if this Rhino has no known parent
    /** Constructor : an instance born in country c with parent p.
     * Precondition : c is not null . */
    public Rhino(String c, Rhino p) {
        co = c;
        parent = p;
    }
    /** Return the number of Rhinos in this Rhino 's family that
    were
     * born in country c. This Rhino 's family consists of this
    Rhino , its
     * parent , its parent 's parent , its parent 's parent 's parent ,
    etc . */
    public int numCountry(String c) {
        if (parent == null){return co.equals(c) ? 1:0;}
        return(co.equals(c) ? 1:0) + parent.numCountry(c);
    }
}

到目前為止,這是我的 JUnit 測試:

import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class RhinoTest {

    @Test
    public void testCountry() {
        Rhino testCP = new Rhino("USA", null);
        assertEquals("USA", testCP.numCountry(""));
        assertNotEquals(testCP, null);
    }
}

試試這個基本測試,讓你開始:

public void testCountry() {

    Rhino rA = new Rhino("USA", null);
    Rhino rB = new Rhino("USA", rA);
    Rhino rC = new Rhino("CANADA", rB);
    Rhino rD = new Rhino("USA", rC);

    int expectedResult = 3;
    assertEquals(expectedResult, rD.numCountry("USA"));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM