Я получаю это org.mockito.exceptions.misusing.UnfinishedStubbingException
, но на основе всех сообщений и описаний, которые я могу найти в Интернете, это не имеет смысла.Mockito/PowerMockito: Weird Stubbing Exception
Исключительный метод утверждает, что thenReturn
может отсутствовать, но это не так. Я оставил цель обеими способами в моем примере ниже: doReturn
и thenReturn
. Ни один из них не работал. И с тем же сообщением об исключении.
Кроме того, нет встроенных издевок. Я подготовил все статические классы и использую PowerMockitoRunner.
Я не могу найти выход. Кто-нибудь может помочь мне узнать, что происходит?
Редактировать: Я забыл упомянуть, что использую Mockito 1.8.5 и PowerMockito 1.4.10.
Полное исключение:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:31)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. although stubbed methods may return mocks, you cannot inline mock creation (mock()) call inside a thenReturn method (see issue 53)
at br.com.tests.email.EnvioCompartilhamento.mockCaptcha(EnvioCompartilhamento.java:120)
at br.com.tests.email.EnvioCompartilhamento.setup(EnvioCompartilhamento.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Мой тестовый класс. Код строки добавляется 10 по 10 (или вид):
006 --> import br.com.common.MyProperties;
import br.com.struts.email.EnvioDeEmail;
import br.com.struts.email.forms.FormularioParaCompartilhamento;
import br.com.util.UrlUtil;
010 --> import br.com.popular.commons.Publications;
import br.com.popular.commons.utils.escenic.RetrievingObjects;
import com.captcha.Captcha;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
020 --> import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import static org.junit.Assert.assertNull;
030 --> import static org.junit.Assert.fail;
import static org.mockito.Matchers.*;
import static org.powermock.api.mockito.PowerMockito.*;
040 --> @RunWith(PowerMockRunner.class)
@PrepareForTest({ Captcha.class, RetrievingObjects.class, UrlUtil.class })
public class EnvioCompartilhamento {
@Mock
private ActionMapping mapping;
@Mock
private HttpServletRequest request;
050 --> @Mock
private HttpServletResponse response;
private FormularioParaCompartilhamento formulario;
@Before
public void setup() throws NoSuchMethodException, NoSuchFieldException, IOException {
mockStaticClasses();
mockRequestBehavior();
060 --> mockCaptcha();
mockResponse();
formulario = new FormularioParaCompartilhamento();
}
@Test
public void compartilhamentoComSucesso() {
formulario.setEmailTo("[email protected]");
formulario.setIdArtigo("12345");
070 --> formulario.setIsArtigo(true);
formulario.setMessage("Corpo do email");
formulario.setTitulo("Titulo");
formulario.setUrl("http://www.google.com");
formulario.setCaptcha("ABCD");
EnvioDeEmail email = new EnvioDeEmail();
final ActionForward resultado = email.compartilhamento(mapping, formulario, request, response);
assertNull(resultado);
080 --> }
112 --> private void mockRequestBehavior() {
when(request.getMethod()).thenReturn("POST");
when(request.getHeader("X-FORWARDED-FOR")).thenReturn("User IP");
}
private void mockCaptcha() {
120 --> HttpSession session = mock(HttpSession.class);
doReturn(session).when(request).getSession();
Captcha captcha = Mockito.mock(Captcha.class);
doReturn(captcha).when(session).getAttribute("captcha");
doReturn(true).when(captcha).isInputValid(anyString());
}
private void mockStaticClasses() {
final MyProperties myProperties = mock(MyProperties.class);
130 --> mockStatic(RetrievingObjects.class);
when(RetrievingObjects.componentFromPublicationAtSystemScope(any(Publications.class), eq("EmailProperties"), eq(MyProperties.class))).
thenReturn(myProperties);
mockStatic(UrlUtil.class);
doNothing().when(UrlUtil.class);
}
private void mockResponse() throws IOException {
PrintWriter writer = mock(PrintWriter.class);
140 --> doReturn(writer).when(response).getWriter();
}
}
Где в тесте на линии 120? – hotzst
Извините. Я отредактирую свой пост, чтобы добавить строки кода. –
@SidneydeMoraes пытается изменить вашу линию 121 на: 'когда (request.getSession()). ThenReturn (session);'. –