Andy Ho
Andy Ho

Reputation: 179

Junit The null test

The teacher gave us an example to test our code, but it gave me an error, if anyone can figure out why it gives me the error, i'll appreciate...

public int compareTo(player other) {
    // TODO Auto-generated method stub
    if (points < other.points) return -1;
    if (points > ohter.points) return 1;
    return 0;
}

public void setPoints(int points) {
    this.points = points;
}

The result of the test:

java.lang.Exception: Unexpected exception, expected <java.lang.IllegalArgumentException> but was <java.lang.Error>.

The test:

@Test(expected=IllegalArgumentException.class)
public void theNullTest(){
    player2 = null;

    player1.setPoints(4);
    player1.compareTo(joueur2);
}

Upvotes: 1

Views: 1144

Answers (3)

Jason C
Jason C

Reputation: 40315

If you actually do have joueur2 instead of player2 in the snippet, it could be seeing an "unresolved compilation error" (which is a java.lang.Error) instead of the expected IllegalArgumentException (which is not a java.lang.Error), as that code would not compile as-is.

If that's the case, please make sure your code actually compiles before testing it (in this case, fix "joueur2"), and do not disregard compiler errors during build.

Upvotes: 2

slartidan
slartidan

Reputation: 21566

Your code contained typos, missing variable declarations and did not match all naming conventions.

If Java encounters compilation problems, than it throws an Error - not the expected Exception, that you were looking for.

I fixed the code, here you are:

package snippet;

import org.junit.Test;

public class Snippet {
    @Test(expected = IllegalArgumentException.class)
    public void theNullTest() {
        Player player1 = new Player();
        Player player2 = null;

        player1.setPoints(4);
        player1.compareTo(player2);
    }
}

class Player {

    private int points;

    public int compareTo(Player other) {
        if (other == null) throw new IllegalArgumentException("Cannot compare a player to null");

        if (points < other.points)
            return -1;
        if (points > other.points)
            return 1;
        return 0;
    }

    public void setPoints(int points) {
        this.points = points;
    }

}

Upvotes: 1

Ypnypn
Ypnypn

Reputation: 931

Java has no way of knowing what's an invalid argument and what is not, so if you want the right exception to get thrown, you'll have to throw it yourself (full code below). If you don't, then when calling other.points, you're asking for a variable belonging to a nonexistent object. This throws an NullPointerException.

public int compareTo(player other) {
    // TODO Auto-generated method stub
    if (other == null)
        throw new IllegelArgumentException();
    if (points < other.points) return -1;
    if (points > ohter.points) return 1;
    return 0;
}

Upvotes: 0

Related Questions