I was trying to develop some code using TDD, but stumbled on a weird behavior: setUp and tearDown doesn't seem to be "cleaning up" after each test is executed. I expected each test (marked with @Test annotation) to be executed at a random order, one after the other, without influencing each other. With that in mind, I don't understand what is happening as it seems like one specific test (testaSomarMao) is influencing another specific test (testaSplit). The testaSplit test is failling on the first assert: I expected value 6, but I'm getting 9. Anybody can explain me what is going on?
JogadorTest.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JogadorTest{
private static Jogador p1;
public JogadorTest(){
}
@Before
public void setUp(){
p1 = new Jogador();
}
@After
public void tearDown(){
p1 = null;
}
@Test
public void testaGetNome(){
assertEquals(null, p1.getNome());
}
@Test
public void testaGetPontos(){
assertEquals(0, p1.getPontos());
}
@Test
public void testaSetNome(){
p1.setNome("Lucas");
assertEquals("Lucas", p1.getNome());
}
@Test
public void testaSomarMao(){
p1.comprarCarta(1);
assertEquals(3, p1.somarMao(1));
}
@Test
public void testaSplit(){
p1.comprarCarta(1);
p1.comprarCarta(1);
assertEquals(6, p1.somarMao(1));
p1.split();
assertEquals(p1.somarMao(1), p1.somarMao(2));
}
}
Jogador.java
public class Jogador {
private static String nome;
private int pontos;
private static int mao[] = new int[13];
private static int mao2[] = new int[13];
public void parar() {
}
public void setNome(String novoNome){
nome = novoNome;
}
public static int getPontos() {
return 0;
}
public static void split() {
//Usamos mao2 para garantir que soh ocorra um split.
if(mao[0] == mao[1] && mao2[0] == 0){
mao2[0] = mao[1];
mao[1] = 0;
}
}
public void fecharJogo() {
}
public String getNome() {
return nome;
}
public static int somarMao(int maoEscolhida){
int soma = 0;
int cartasNaMao[];
if(maoEscolhida == 2)
cartasNaMao = mao2;
else
cartasNaMao = mao;
for(int i = 0; i < cartasNaMao.length; i++)
soma += cartasNaMao[i];
return soma;
}
public static void comprarCarta(int maoEscolhida){
int carta = 3; // random futuramente
int cartasNaMao[];
if(maoEscolhida == 2)
cartasNaMao = mao2;
else
cartasNaMao = mao;
for(int i = 0; i < cartasNaMao.length; i++){
if(cartasNaMao[i] == 0) {
cartasNaMao[i] = carta;
break;
}
}
}
}