I'm getting this org.mockito.exceptions.misusing.UnfinishedStubbingException but based on all posts and descriptions I could find at internet, it doesn't seem to make sense.
The exception method states a thenReturn may be missing, but it's not. I left on purpose both ways on my example code below: doReturn and thenReturn. None of them worked. Both with the very same exception message.
Also, there are no inline mocks. I prepared all static classes and am using PowerMockitoRunner.
I can't find any way out. Any one can help me find out what's going on?
Edit: I forgot to mention I'm using Mockito 1.8.5 and PowerMockito 1.4.10.
Full exception:
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)
My test class. Code lines added 10 by 10 (or sort of):
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("teste#teste.com");
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();
}
}
doNothing().when(UrlUtil.class);
This doesn't mean anything to Mockito or PowerMock; you need to specify the specific call you want to mock. That makes this stubbing unfinished. See the PowerMockito when docs as an example.
However, Mockito can't tell on this line that your stubbing is unfinished—it can only raise an error when you interact with it, so it only detects the error condition later, in your mockCaptcha method.
To fix this, either finish your UrlUtil stub as follows (I specify PowerMockito to distinguish from Mockito.doNothing, though it looks like you have your static imports correct):
PowerMockito.doNothing().when(UrlUtil.class);
UrlUtil.methodYouWantToMock();
Or, to make UrlUtil suppress all its behavior by default, remove that doNothing line and put a default answer into your mockStatic call:
mockStatic(UrlUtil.class, RETURNS_SMART_NULLS);
Related
Good day I've got class with 2 methods: first is public GetLeadRequestsList - I want to test it, and second is private LeadRequestListResponse - used by first method. I mocked second method and called first one. Code of my test is here. When I run testGetLeadRequestsList, I catched
org.powermock.reflect.exceptions.FieldNotFoundException: No static field of type "org.mockito.internal.progress.MockingProgress" could be found in the class hierarchy of org.mockito.Mockito.
at org.powermock.reflect.internal.matcherstrategies.FieldTypeMatcherStrategy.notFound(FieldTypeMatcherStrategy.java:40)
at org.powermock.reflect.internal.WhiteboxImpl.findSingleFieldUsingStrategy(WhiteboxImpl.java:502)
at org.powermock.reflect.internal.WhiteboxImpl.findFieldInHierarchy(WhiteboxImpl.java:455)
at org.powermock.reflect.internal.WhiteboxImpl.getInternalState(WhiteboxImpl.java:576)
at org.powermock.reflect.Whitebox.getInternalState(Whitebox.java:347)
at org.powermock.api.mockito.internal.PowerMockitoCore.getMockingProgress(PowerMockitoCore.java:45)
at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
at org.powermock.api.mockito.PowerMockito.doReturn(PowerMockito.java:790)
at ru.sbrf.sbi.ufs.business.rest.api.LeadRequestsControllerImplTest.setUp(LeadRequestsControllerImplTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:514)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:589)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:782)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
error in testclass is in the String:
doReturn(leadRequestsResponse).when(mock, "LeadRequestListResponse", ArgumentMatchers.anyBoolean());
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.sbrf.sbi.ufs.poi.vo.ErrorMessage;
import ru.sbrf.sbi.ufs.poi.vo.LeadRequestData;
import ru.sbrf.sbi.ufs.poi.vo.LeadRequestListResponse;
import ru.sbrf.sbi.ufs.poi.vo.ResponseStatus;
import java.util.ArrayList;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.testng.Assert.*;
public class LeadRequestsControllerImplTest {
#Spy
LeadRequestsControllerImpl mock = new LeadRequestsControllerImpl();
LeadRequestListResponse leadRequestsResponse;
#BeforeMethod
public void setUp() throws Exception {
leadRequestsResponse = new LeadRequestListResponse();
leadRequestsResponse.setResponseStatus(new ResponseStatus().withStatusCode(200L));
ArrayList<LeadRequestData> requests = new ArrayList<>();
requests.add(LeadRequestData.builder()
.companyName("НПО Помощь")
.lastName("Помоги")
.firstName("Себе")
.secondName("Сам")
.build());
leadRequestsResponse.setRequests(requests);
doReturn(leadRequestsResponse).when(mock, "LeadRequestListResponse", ArgumentMatchers.anyBoolean());
}
#Test
public void testGetLeadRequestsList() {
try {
String result = mock.getLeadRequestsList();
ObjectMapper mapper = new ObjectMapper();
String expect = mapper.writeValueAsString(leadRequestsResponse);
assertEquals(expect, result,"GetLeadRequestsList isn't correct.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Maybe, anybody know how to check with Error.
Thank's in advance
I suppose you use not correct versions of mockito-core and powermock-api-mockito. Because FieldNotFoundException could be if using not compatible versions of these libraries. Please use support versions chart - https://github.com/powermock/powermock/wiki/Mockito#supported-versions
So you need check your versions and correct it.
Also you should do next things:
Add #RunWith(PowerMockRunner.class) and #PrepareForTest(LeadRequestsControllerImpl.class) before LeadRequestsControllerImplTest
Change from TestNG #BeforeMethod to JUnit annotations (for example #BeforeClass) because you can't mixed it.
I am attempting to write a #SpringBootTest which will both issue REST requests and mock responses. I want to do this because my spring application receives REST requests and in response it fetches information from another source using REST. I would like to trigger my application by initiating a REST GET (MockMvc), but would also like to mock the other source's response (MockRestServiceServer).
Here is a sanitized version of the test, with my application removed:
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#Slf4j
#ExtendWith(SpringExtension.class)
#SpringBootTest
#AutoConfigureMockMvc
class RestTest {
private static final String URI = "/my-test-uri";
private static final String RESPONSE = "my-response";
#Autowired
private MockMvc mockMvc;
#Test
void testRest() throws Exception {
log.info("Initiating request for GET {}", URI);
mockMvc.perform(get(URI))
.andExpect(status().isOk())
.andExpect(content().string(containsString(RESPONSE)));
}
#TestConfiguration
static class TestConfig {
#Primary
#Bean
public RestTemplateBuilder restTemplateBuilder() {
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);
server.expect(requestTo(URI))
.andRespond(withSuccess(RESPONSE, MediaType.APPLICATION_JSON));
log.info("Mocking response to GET {}: {}", URI, RESPONSE);
RestTemplateBuilder mockBuilder = mock(RestTemplateBuilder.class);
when(mockBuilder.build()).thenReturn(restTemplate);
return mockBuilder;
}
}
}
The test fails because it does not receive the response defined in TestConfig.restTemplateBuilder. I am providing both the REST requestor (testRest() method) and the REST responder (TestConfig.restTemplateBuilder). What am I doing wrong?
Here's the failure:
Status expected:<200> but was:<404>
Expected :200
Actual :404
<Click to see difference>
java.lang.AssertionError: Status expected:<200> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at com.mycompany.RestTest.testRest(RestTest.java:54)
...
at java.base/java.lang.Thread.run(Thread.java:830)
I am trying to run a simple bdd test using behave and serenity but i am getting a initialization error. It seems as though there is a package class which is null but i cannot figure out which one or is there something wrong with way i am initialising my code.
I have been serenity bdd documentation online
https://serenity-bdd.github.io/theserenitybook/latest/jbehave.html
directory tree
new output
Appreciate the help :)
Below is the stack trace and code.
ava.lang.NullPointerException
at net.serenitybdd.jbehave.RootPackage.forPackage(RootPackage.java:8)
at net.serenitybdd.jbehave.SerenityStories.getRootPackage(SerenityStories.java:220)
at net.serenitybdd.jbehave.SerenityStories.stepsFactory(SerenityStories.java:88)
at org.jbehave.core.ConfigurableEmbedder.configuredEmbedder(ConfigurableEmbedder.java:130)
at net.serenitybdd.jbehave.runners.SerenityReportingRunner.<init>(SerenityReportingRunner.java:68)
at net.serenitybdd.jbehave.runners.SerenityReportingRunner.<init>(SerenityReportingRunner.java:62)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.requests.ClassRequest.createRunner(ClassRequest.java:28)
at org.junit.internal.requests.MemoizingRequest.getRunner(MemoizingRequest.java:19)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
test.class
import net.thucydides.core.annotations.Managed;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.When;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
public class test {
#Managed()
WebDriver webDriver;
#Steps
GoogleSteps googleSteps;
#When("I open the page $value")
public void itest(String value) {
googleSteps.sendvalue(value);
}
}
GooglePage.class
import net.serenitybdd.core.annotations.findby.By;
import net.thucydides.core.annotations.DefaultUrl;
import net.thucydides.core.annotations.Step;
import net.thucydides.core.pages.PageObject;
import org.openqa.selenium.Keys;
#DefaultUrl("http://www.google.com")
public class GooglePage extends PageObject {
public void searchGoogle (String q) {
find(By.name("q")).sendKeys(q, Keys.ENTER);
}
}
GoogleSteps.class
import net.thucydides.core.annotations.Step;
public class GoogleSteps {
GooglePage googlePage;
#Step
public void open_page() {
googlePage.open();
}
#Step
public void sendvalue (String value) {
googlePage.searchGoogle(value);
}
}
GoogleRunner.class
import net.serenitybdd.jbehave.SerenityStory;
public class GoogleRunner extends SerenityStory {
}
serenity.properties file
webdriver.driver=chrome
webdriver.chrome.driver = /Users/aneesaiqbal/Downloads/chromedriver-2.exe
login.story
Narrative:
Testing google
Scenario: lets google
When I open the page hello
We are using Powermockito with Mockito to mock some static classes. There seems to be java.lang.ExceptionInInitializerError thrown every time.
Can you help me identify where the problem is?
Java class under test
package com.myproject.myproduct.search.domain;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
public class MyQueryBuilder {
public MultiMatchQueryBuilder getMultiMatchQueryBuilder() {
MultiMatchQueryBuilder builder = QueryBuilders.multiMatchQuery("term", "field1");
builder.field("field1",200.9f);
return builder;
}
}
Junit test with Powermock runner
package com.myproject.myproduct.search.domain;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(QueryBuilders.class)
public class MyQueryBuilderTest {
private MyQueryBuilder myQueryBuilder;
#Test
public void test() {
PowerMockito.mockStatic(QueryBuilders.class);
MultiMatchQueryBuilder builder = PowerMockito.mock(MultiMatchQueryBuilder.class);
}
}
That's it. The test code does not work as soon as I try to mock
MultiMatchQueryBuilder.
This is the Exception:
java.lang.ExceptionInInitializerError at
org.elasticsearch.common.logging.DeprecationLogger.(DeprecationLogger.java:138)
at org.elasticsearch.common.ParseField.(ParseField.java:35)
at
org.elasticsearch.index.query.AbstractQueryBuilder.(AbstractQueryBuilder.java:53)
at
sun.reflect.GeneratedSerializationConstructorAccessor7.newInstance(Unknown
Source) at
java.lang.reflect.Constructor.newInstance(Constructor.java:423) at
org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59) at
org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128)
at
org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63)
at
org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)
at
org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:60)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:143)
at
com.spartasystems.stratas.search.domain.MyQueryBuilderTest.testBoostSetProperly(MyQueryBuilderTest.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68) at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at
org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
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:122)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at
org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.NullPointerException at
org.elasticsearch.Build.(Build.java:47) ... 41 more
Process finished with exit code 255
Note:
The source code of actual underlying elasticsearch classes can be found here
https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/index/query/QueryBuilders.java
and
https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/index/query/MultiMatchQueryBuilder.java
When calling with mocks org.elasticsearch.Build#getElasticsearchCodebase
Build.class.getProtectionDomain().getCodeSource().getLocation()
returns null because the code has no location (Dynamic method generated by cglib.)
So when initializing org.elasticsearch.Build during your mock code using
final URL url = getElasticsearchCodebase(); // url is null
final String urlStr = url.toString(); // null pointer exception.
Of course, the mock will not success and throw ExceptionInInitializerError which indicates an exception occurred during evaluation of a static initializer or the initializer for a static variable.
You can easily reproduce this exception using following code:
#RunWith(PowerMockRunner.class)
#PrepareForTest({QueryBuilders.class})
public class MyQueryBuilderTest {
#Test
public void test() {
final Build current = Build.CURRENT;
}
}
I'm having a really hard time getting Jersey, AppEngine and JUnit to work. Current error is following:
No API environment is registered for this thread.
I'm doing following:
Loading the helper.setUp() (LocalDataStoreService) over JUnit #Before annotation
Creating an instance of the Grizzly Webserver over the JUnit #Before annotation
Executing the testCreateCard test
Stopping the Grizzly Webserver
Running the helper.tearDown() method over JUnit #After annotation
I launch (Run as) Junit Test with Eclipse Indigo (I include the jars over the Java BuildPath).
It seems like Jersey or the Grizzly Webcontainer is opening new threads which doesn't work with the local datastore methods helper.setUp() and helper.tearDown().
I have found a few questions/answers but not related to using AppEngine with Jersey.
Is there anyone that can help? Is a setup with Jersey and AppEngine and JUnit actually possible? I tried several possibilities with rest-assured and jersey-test-framework but all tries ended up in errors and debugging and also a post in to the AppEngine Mailinglist without any results.
My last hope is my current setup with:
Grizzly 2.1 (provided by Jersey)
Jersey 1.12
JUnit 4.10
Stacktrace is following:
java.lang.NullPointerException: No API environment is registered for this thread.
at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppId(DatastoreApiHelper.java:86)
at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppIdNamespace(DatastoreApiHelper.java:96)
at com.google.appengine.api.datastore.Key.<init>(Key.java:106)
at com.google.appengine.api.datastore.Key.<init>(Key.java:90)
at com.google.appengine.api.datastore.Key.<init>(Key.java:86)
at com.google.appengine.api.datastore.Entity.<init>(Entity.java:125)
at com.google.appengine.api.datastore.Entity.<init>(Entity.java:106)
at org.datanucleus.store.appengine.DatastoreFieldManager.<init>(DatastoreFieldManager.java:189)
at org.datanucleus.store.appengine.DatastorePersistenceHandler.insertPreProcess(DatastorePersistenceHandler.java:354)
at org.datanucleus.store.appengine.DatastorePersistenceHandler.insertObjects(DatastorePersistenceHandler.java:267)
at org.datanucleus.store.appengine.DatastorePersistenceHandler.insertObject(DatastorePersistenceHandler.java:256)
at org.datanucleus.state.JDOStateManagerImpl.internalMakePersistent(JDOStateManagerImpl.java:3185)
at org.datanucleus.state.JDOStateManagerImpl.makePersistent(JDOStateManagerImpl.java:3161)
at org.datanucleus.ObjectManagerImpl.persistObjectInternal(ObjectManagerImpl.java:1298)
at org.datanucleus.ObjectManagerImpl.persistObject(ObjectManagerImpl.java:1175)
at org.datanucleus.jdo.JDOPersistenceManager.jdoMakePersistent(JDOPersistenceManager.java:669)
at org.datanucleus.jdo.JDOPersistenceManager.makePersistent(JDOPersistenceManager.java:694)
at com.acolsolutions.loyaltycard.dataobjects.CardDAO.create(CardDAO.java:23)
at com.acolsolutions.loyaltycard.resources.CardResource.create(CardResource.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1483)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1414)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1363)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1353)
at com.sun.jersey.server.impl.container.grizzly2.GrizzlyContainer._service(GrizzlyContainer.java:215)
at com.sun.jersey.server.impl.container.grizzly2.GrizzlyContainer.service(GrizzlyContainer.java:185)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:163)
at org.glassfish.grizzly.http.server.HttpHandlerChain.service(HttpHandlerChain.java:207)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:163)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:164)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:265)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:134)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:78)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:816)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:111)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:566)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:546)
at java.lang.Thread.run(Unknown Source)
My Jersey Test class looks following:
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.UriBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.Client;
import org.codehaus.jettison.json.JSONObject;
public class CardResourceTests {
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
new LocalDatastoreServiceTestConfig());
private HttpServer httpServer;
private URI uri;
#Before
public void setUp() throws Exception {
helper.setUp();
uri = UriBuilder.fromUri("http://localhost/").port(9998).build();
ResourceConfig rc = new PackagesResourceConfig("com.acolsolutions.loyaltycard.resources");
httpServer = GrizzlyServerFactory.createHttpServer(uri, rc);
}
#After
public void tearDown() throws Exception {
helper.tearDown();
httpServer.stop();
}
#Test
public void testCreate() {
boolean thrown = false;
Client client = Client.create();
WebResource webResource = client.resource(uri);
JSONObject card = new JSONObject();
try {
card.put("id", "1")
.put("name", "Name of Card")
.put("code", "123456")
.put("codeTypeId", "1")
.put("cardProviderName", "The Card Provider")
.put("picturePath", "provider.jpg")
.put("cardProviderUrl", "http://www.provider.com")
.put("creationDate", "Sun Jun 10 08:55:14 UTC 2012")
.put("modificationDate","Sun Jun 10 08:55:14 UTC 2012");
webResource.path("cards").type("application/json").post(card);
} catch(Exception e) {
e.printStackTrace();
thrown = true;
}
assertEquals("Result", false, thrown);
}
}
Why are you trying to use grizzly if you're using appengine? Appengine is your container, not grizzly..