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.
Related
I'm trying to connect to MongoDB in Jmeter by using JSR223 Sampler. Here is my code:
import com.mongodb.MongoClientURI;
import com.mongodb.MongoClient;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.ConnectionString;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.Arrays;
import com.mongodb.Cursor;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
try {
MongoClientURI connectionString = new MongoClientURI("mymongodb.com:27017");
MongoClient mongoClient = MongoClients.create(connectionString);
MongoDatabase database = mongoClient.getdatabse("mydatbase");
MongoCollection<Document> collection = database.getCollection("employee");
}
catch (Throwable ex) {
log.error("Error in Beanshell", ex);
throw ex;
}
I'm getting error:
ERROR o.a.j.p.j.s.J.JSR223 Sampler: Error in Beanshell
groovy.lang.MissingMethodException: No signature of method: static com.mongodb.client.MongoClients.create() is applicable for argument types: (com.mongodb.MongoClientURI) values: [mymongodb.com:27017]
Possible solutions: create(), create(com.mongodb.ConnectionString), create(com.mongodb.MongoClientSettings), create(java.lang.String), create(com.mongodb.ConnectionString, com.mongodb.MongoDriverInformation), create(com.mongodb.MongoClientSettings, com.mongodb.MongoDriverInformation)
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1518) ~[groovy-all-2.4.16.jar:2.4.16]
at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1504) ~[groovy-all-2.4.16.jar:2.4.16]
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:52) ~[groovy-all-2.4.16.jar:2.4.16]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47) [groovy-all-2.4.16.jar:2.4.16]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116) [groovy-all-2.4.16.jar:2.4.16]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128) [groovy-all-2.4.16.jar:2.4.16]
at Script11.run(Script11.groovy:44) [script:?]
at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:321) [groovy-all-2.4.16.jar:2.4.16]
at org.codehaus.groovy.jsr223.GroovyCompiledScript.eval(GroovyCompiledScript.java:72) [groovy-all-2.4.16.jar:2.4.16]
at javax.script.CompiledScript.eval(CompiledScript.java:89) [java.scripting:?]
at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:223) [ApacheJMeter_core.jar:5.1.1 r1855137]
at org.apache.jmeter.protocol.java.sampler.JSR223Sampler.sample(JSR223Sampler.java:71) [ApacheJMeter_java.jar:5.1.1 r1855137]
at org.apache.jmeter.threads.JMeterThread.doSampling(JMeterThread.java:622) [ApacheJMeter_core.jar:5.1.1 r1855137]
at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:546) [ApacheJMeter_core.jar:5.1.1 r1855137]
at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:486) [ApacheJMeter_core.jar:5.1.1 r1855137]
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:253) [ApacheJMeter_core.jar:5.1.1 r1855137]
at java.lang.Thread.run(Thread.java:834) [?:?]
Anyone has any ideas? Many Thanks!
Your code relies on a diamond operator which is not supported in Beanshell.
Be aware that starting from JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting so consider choosing groovy as the scripting language and your code should start working normally
You might also be interested in MongoDB Performance Testing with JMeter article
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;
}
}
Dependencies used for this:
cucumber-core-1.2.4
cucumber.html-0.2.3
cucumber-java-1.2.4
cucumber-junit-1.2.4
junit-4.11
gherkin-2.12.2
cucumber-jvm-deps-1.0.3
I recently cleaned up my dependencies folder structure and think I might have misplaced something, but my problem is an instantiation issue that doesn't make sense as it seems I have my ducks in a row on the cucumber side. Here is the stack trace:
cucumber.runtime.CucumberException: Failed to instantiate class cucumber.feature.LoginandMeetingCreation
at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:46)
at cucumber.runtime.java.DefaultJavaObjectFactory.getInstance(DefaultJavaObjectFactory.java:32)
at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
at cucumber.runtime.Runtime.runStep(Runtime.java:299)
at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:121)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:40)
... 11 more
Caused by: java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:770)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:96)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:71)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:45)
at cucumber.feature.LoginandMeetingCreation.<init>(LoginandMeetingCreation.java:19)
... 16 more
Here is my cucumber runner that sets up the feature files, but never executes the glue command. My package cucumber.feature contains my step definition file LoginandMeetingCreation.java file:
package cucumberInitialization;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {"pretty" , "json:target/cucumber.json"},
features = {"src/cucumber/"},
monochrome = true,
glue = {"cucumber.feature"}
)
public class cucumberRunner {
}
Feature file with steps:
Feature: Create a meeting and fill in the necessary text fields
Scenario: As a user, login and create a meeting
Given I navigated to the site
When I login and select an org
Then Create a meeting
And finally my step definitions:
package cucumber.feature;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginandMeetingCreation {
WebDriver chromeDriver = null;
WebDriver ieDriver = null;
//open IE and Chrome browsers and go to Website
#Given("^I navigated to the site$")
public void navigateToWebsite() throws Throwable{
throw new PendingException();
}
//login users
#When("^I login and select an org$")
public void userLogin() throws Throwable{
throw new PendingException();
}
#Then("^Create a meeting$")
public void meetingCreation() throws Throwable{
throw new PendingException();
}
}
Any advice?
Thanks GalexMES.
You were right, I had forgotten I had deleted a bulk amount and it dawned on me I was creating an object that cannot accept a null value. When I had written WebDriverWait wait = new WebDriverWait(ieDriver, 5); ieDriver was null, which causes the NPE. Once I create the ieDriver object from a non null value the expected behavior is executed.
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);