quinta-feira, 5 de junho de 2008

Resolvendo o problema do finally no EclEMMA

A algum tempo reclamei do meu colega EclEMMA aqui, acontece que fiz uma pergunta num forum do produto, e mesmo com o meu inglês digno de um índio, obtive uma boa resposta:

"Hi, the yellow line is an artifact of the underlying coverage technology which is based on byte code instrumentation. "Finally" statements only exist in Java source code, the Java compiler creates corresponding control structured in byte code. The finally block is actually executed in two different cases: In case of normal execution and in case of an exception within the try block. You're test code follows only one the these paths, therefor the line is marked yellow (partial execution)."

Muito bacana, dessa forma percebi que tenho que deixar o método disparar a exceção, caso ela aconteça, e tenho que verifica-la no método de teste.

Usando o mesmo exemplo, eis a forma correta de testar e obter o resultado correto com o EclEMMA :

1: public class StupidClass {
2:
3: public String falar() throws Exception{
4:
5: try
6: {
7: System.out.println("try: ");
8: System.out.println("oyeah!");
9: }
10: catch (Exception e)
11: {
12: System.out.println("catch");
13: e.printStackTrace();
14: throw e;
15: }
16: finally
17: {
18: System.out.println("ogou!");
19: }
20:
21: return "oh! fezes";
22: }
23: }
e seu teste fica assim:

0: import static org.junit.Assert.assertEquals;
1: import static org.junit.Assert.assertNotNull;
2:
3: import org.junit.Before;
4: import org.junit.Test;
5:
6: public class TestStupidClass {
7:
8: StupidClass stupidClass = null;
9:
10: @Before
11: public void antes(){
12: stupidClass = new StupidClass();
13: }
14:
15: @Test
16: public void falarTest() throws Exception{
17:
18: assertEquals("Test 1", stupidClass.falar(), "oh! fezes");
19:
20: Exception exp = null;
21:
22: try{
23: stupidClass.falar();
24: }catch (Exception e) {
25: exp = e;
26: }
27:
28: assertNotNull("Test 2", exp);
29:
30: }
31: }
Obrigado ao pessoal do EclEMMA.