Estou fazendo uma lista de exercícios e estou com dúvida no seguinte:
Exercício 3 – O método verify, do pacote org.mockito.Mockito.verify, é usado para checar a quantidade de vezes que um método é invocado. Adicionar na classe ATest um teste para checar se ao invocar o método area(2) o método pi() é invocado exatamente 1 vez.
A classe a ser testada é a seguinte:
package aula;
public abstract class A {
public long fatorial(long n) {
if (n <= 1) {
return 1;
}
return n * fatorial(n - 1);
}
public abstract Object calc(Object x, Object y) throws
NullPointerException, Exception;
public void msg(String txt) {
}
public double area(double r) {
return 2 * pi() * r;
}
public double pi() {
return Math.PI;
}
public double pow() {
return pi() * pi();
}
public abstract int inc();
}
O teste que eu criei utilizando o JUnit 4 para resolver o exercício três é o seguinte:
package aula;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
public class ATest {
@Mock
private A a = null;
@Before
public void setUp() throws Exception {
a = mock(A.class);
}
//Exercício 1
@Test
public void test1() throws Exception{
//{a: 2, b: 2, esperado: 4}
when(a.calc(2, 2)).thenReturn(4);
}
@Test
public void test2() throws Exception{
//{a: “x”, b: “y”, esperado: “xy”}
when(a.calc("x", "y")).thenReturn("xy");
}
@Test(expected = NullPointerException.class)
public void test3() throws Exception{
//{a: null, b: “y”, esperado: NullPointerException}
when(a.calc(null, "y")).thenThrow(new NullPointerException());
assertSame(1, a.calc(null, "y"));
}
@Test(expected = Exception.class)
public void test4() throws Exception{
//{a: “2”, b: 2, esperado: Exception}
when(a.calc("2", 2)).thenThrow(new Exception());
assertSame(1, a.calc("2", 2));
}
//Exercício 2
@Test(expected = Exception.class)
public void test5() throws Exception {
doThrow(new Exception("Exercício 2 - Teste de Exceção")).when(a).msg(null);
}
//Exercício 3
@Test
public void test6() throws Exception{
when(a.area(2.0)).thenReturn(2.0);
}
@Test
public void test7() throws Exception {
when(a.area(2)).thenReturn(2.0);
//when(a.area(2.0)).thenCallRealMethod();
verify(a, times(0)).pi();
//assertSame(2.0, a.area(2));
verify(a, times(1)).pi();
}
}
Como podemos ver, estou bem confusa com essa questão, pesquisei em muitas coisas e não consegui sanar minha dúvida. Quando tento rodar esse teste, o resultado é azul e não verde como esperado. Aparece o seguinte erro:
Wanted but not invoked: Actually, there were zero interactions with this mock.
Se alguém puder me me ajudar, explicando com a classe que disponibilizei ali em cima, eu agradeço! Eu realmente não estou conseguindo fazer ):