mpz mpz - 6 months ago 8
Java Question

Unexpected failure on JUnit test when using assertEquals

I want to make a simple test to check the name attribute of my class

Player
using JUnit's
assertEquals
method. When I run the JUnit test, I get a failure with a warning(AssertionFailedError: No tests found in PlayerTest), what am I doing wrong?

public class Player {
private String name;
private int id;

public Player(int id){
this.setId(id);
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
}

public class PlayerTest extends TestCase {

@Test
public void NameTest(){
Player player = new Player(1);
player.setName("Roberto");
String name = "Roberto";
assertEquals(name, player.getName());
}
}

Answer

I assume this is because you wrote a Junit 3 style test case (using extends TestCase) instead of the annotation driven Junit 4 style.

Here is a junit 4 style test would look like:

import junit.framework.TestCase;


import org.junit.Test;
import static org.junit.Assert.assertEquals;


public class PlayerTest  {

    @Test
    public void NameTest(){
        Player player = new Player(1);
        player.setName("Roberto");
        String name= "Roberto";
        assertEquals(name,player.getName());
    }

}

Edit: See Sunil's answer to make it work in Junit-3 style.