简体   繁体   中英

Recursive JUnit Test

So, I'm trying to write 3 test cases to find if the recursive method I wrote is right. I'm not too good with JUnit but this is what I got so far.

How can I show that my recursive method is right (if it is) in JUnit?

Here's my Class:

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);
    }
}

Here's my JUnit Test so far:

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);
    }
}

Try this basic test to get you started :

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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM