I have the following error and I would appreciate if someone can tell me what am I doing wrong. I'm trying to run test in navigateAllMenus.java but the moment the script tries to locate loginLink, it stops and gives me java.lang.NullPointerException in line 28:
_a_LoginPage.loginLink(driver).click();.
I have tried many times with different xpaths for the same element but nothing works. I am at a Jr level and still get confused with certain things. So here's what I have, thank you in advance.
Trace:
java.lang.NullPointerException
at autFwk.navigateAllMenus.test(navigateAllMenus.java:28)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Test case:
package autFwk;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import pagObj._b_HomePage;
import pagObj._a_LoginPage;
public class navigateAllMenus {
#BeforeClass
public static void setUpBeforeClass() throws Exception {
System.setProperty("webdriver.chrome.driver","ChromeDriver/chromedriver.exe");
}
#Test
public void test() {
WebDriver driver = new ChromeDriver();
driver.get("https://www.interaction-design.org/");
_a_LoginPage.loginLink(driver).click();
_a_LoginPage.email(driver).sendKeys("em#ail.com");
_a_LoginPage.password(driver).sendKeys("password");
_a_LoginPage.loginButton(driver).click();
_b_HomePage.Profile(driver).click();
driver.navigate().back();
_b_HomePage.Courses(driver).click();
driver.navigate().back();
_b_HomePage.Community(driver).click();
driver.navigate().back();
_b_HomePage.Logout(driver).click();
assertTrue(_a_LoginPage.loginLink(driver).isDisplayed());
driver.quit();
}
}
Object loginLink is the one that seems to be giving me trouble:
package pagObj;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class _a_LoginPage {
private static WebElement element = null;
public static WebElement loginLink (WebDriver driver){
driver.findElement(By.xpath("//a[#href='https://www.interaction-design.org/login']"));
return element;
You are getting a NullPointerException because in the _a_LoginPage Class you haven't initialized the WebDriver instance i.e. driver and haven't written the constructor. So you have to add the following in the _a_LoginPage Class :
//initialize the WebDriver instance
WebDriver driver;
//constructor
public _a_LoginPage(WebDriver driver)
{
this.driver=driver;
}
Related
I'm trying to run an Appium test with selenium, PageFactory.initElements
this Code works only on JDK Amazon corretto-1.8
getting an error on all higher JDKs. (11,15,19)
My actual Goal is to upgrade my Java project level to JDK 11 or higher.
java.lang.RuntimeException: java.lang.NoSuchMethodException: jdk.proxy2.$Proxy8.proxyClassLookup()
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.prepareAnnotationMethods(AppiumByBuilder.java:84)
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.getFilledValue(AppiumByBuilder.java:91)
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.createBy(AppiumByBuilder.java:147)
at io.appium.java_client.pagefactory.DefaultElementByBuilder.getBys(DefaultElementByBuilder.java:133)
at io.appium.java_client.pagefactory.DefaultElementByBuilder.buildMobileNativeBy(DefaultElementByBuilder.java:175)
at io.appium.java_client.pagefactory.DefaultElementByBuilder.buildBy(DefaultElementByBuilder.java:204)
at io.appium.java_client.pagefactory.AppiumElementLocatorFactory.createLocator(AppiumElementLocatorFactory.java:66)
at io.appium.java_client.pagefactory.AppiumElementLocatorFactory.createLocator(AppiumElementLocatorFactory.java:53)
at io.appium.java_client.pagefactory.AppiumElementLocatorFactory.createLocator(AppiumElementLocatorFactory.java:1)
at org.openqa.selenium.support.pagefactory.DefaultFieldDecorator.decorate(DefaultFieldDecorator.java:56)
at io.appium.java_client.pagefactory.AppiumFieldDecorator.decorate(AppiumFieldDecorator.java:154)
at org.openqa.selenium.support.PageFactory.proxyFields(PageFactory.java:113)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:105)
at stable.NewTest.setUp(NewTest.java:24)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.NoSuchMethodException: jdk.proxy2.$Proxy8.proxyClassLookup()
at java.base/java.lang.Class.getMethod(Class.java:2277)
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.prepareAnnotationMethods(AppiumByBuilder.java:82)
... 35 more
Here is My Code
package stable;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
import io.appium.java_client.pagefactory.iOSXCUITFindBy;
import model.util.AppiumDriverBuilder;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.support.PageFactory;
public class NewTest {
private AppiumDriver driver;
public Po page;
#Before
public void setUp() throws Exception {
driver = new AppiumDriverBuilder().build(false, "testName.getMethodName()");
page = new Po();
PageFactory.initElements(new AppiumFieldDecorator(driver), page);
}
#Test
public void first() {
page.skip_button.click();
}
class Po {
#iOSXCUITFindBy(accessibility = "Skip")
#AndroidFindBy(id = "onboarding_skip_button")
public MobileElement skip_button;
}
}
Fails here: PageFactory.initElements(new AppiumFieldDecorator(driver), page);
I'm using
Appium java client 7.4
maven-surefire-plugin 3.0.05M
Junit 5.4.2
There is a requirement where I have to add extension in browser before running scripts.
For that I decided to use Browser Options (EdgeOptions).Browser option is introduced in selenium 4.
All required dependencies I have already imported but now I am getting exception in PageFactory.initElements.
selenium-api-4.1.1
selenium-chrome-driver-4.1.1
selenium-chromium-driver-4.1.1
selenium-edge-driver-4.1.1
selenium-java-4.1.1
selenium-remote-driver-4.1.1
selenium-support-4.1.1
Do I have to add some other dependencies also?
Message: cucumber.runtime.CucumberException: Failed to instantiate class com.proj.stepdefinitions.common.ConfigTestData
at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:40)
at cucumber.runtime.java.DefaultJavaObjectFactory.getInstance(DefaultJavaObjectFactory.java:26)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:59)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:222)
at cucumber.runtime.Runtime.runHooks(Runtime.java:210)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:200)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:91)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:93)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:37)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cucumber.api.junit.Cucumber.run(Cucumber.java:98)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.reflect.InvocationTargetException
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 cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:34)
... 31 more
Caused by: java.lang.NoSuchMethodError: org.openqa.selenium.support.PageFactory.initElements(Lorg/openqa/selenium/WebDriver;Ljava/lang/Class;)Ljava/lang/Object;
at com.proj.stepdefinitions.common.ConfigTestData.<init>(ConfigTestData.java:115)
... 36 more
ConfigTestData code below :
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import com.step.AfterScenarioScript; //project class
public class ConfigTestData {
//some constants
public static WebDriver driver = null;
//exception here
CommonMethods cm = PageFactory.initElements(driver,
CommonMethods.class);
AfterScenarioScript afterScenarioScript = PageFactory.initElements(driver, AfterScenarioScript.class);
private CreateFile file = PageFactory.initElements(driver, CreateFile.class);
#Before
public void init(Scenario scenario) throws IOException {
prop = Login.readPropertiesFile();
//some code
}
#After
public void afterScenario(Scenario scenario) throws Throwable {
//some code
}
//some utility methods
}
I have checked answers to other similar questions in stack overflow but none of that helped. Could you please help me resolve the issue. I am trying to automate a mobile app. Learning the android app automation stuff. My code is below:
The project structure
Feature File:
Feature: Register for Yammer
Scenario: Sign Up for Yammer App
Given The App is launched
When I click on SignUp button
Then I should see FirstName Lastname EmailId Password field
When I click on SignUp button
Then I should see error
StringsDj.java class
package AppiumdemoDj;
public class StringsDj {
public static String signUpButton = "com.yammer.v1:id/signup_button";
public static String firstName = "com.yammer.v1:id/first_name_edittext";
public static String lastName = "com.yammer.v1:id/last_name_edittext";
public static String emailId = "com.yammer.v1:id/work_email_edittext";
public static String password = "com.yammer.v1:id/password_edittext";
}
SignUpDj.java class
package AppiumdemoDj;
import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import io.appium.java_client.AppiumDriver;
public class SignUpDj {
private WebDriver driver;
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Taking screenshot
#Given("^The App is launched$")
public void the_App_is_launched() throws Throwable
{
DesiredCapabilities capabilities = new DesiredCapabilities();
//capabilities.setCapability("webdriver.gecko.driver", "/Applications/Automation/dependencies/geckodriver");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability("deviceName", "Pixel");
capabilities.setCapability("platformVersion", "8.0.0");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("appPackage", "com.yammer.v1");
capabilities.setCapability("appActivity", "com.yammer.droid.ui.LauncherActivity");
//AppiumDriver wd = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
//wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
}
#When("^I click on SignUp button$")
public void i_click_on_SignUp_Button() throws Throwable
{
driver.findElement(By.id(StringsDj.signUpButton)).click();
FileUtils.copyFile(scrFile, new File("./ScreenShots/"));
}
#Then("^I should see FirstName Lastname EmailId Password field$")
public void i_should_see_FirstName_Lastname_EmailId_Password_field() throws Throwable
{
driver.findElement(By.id(StringsDj.firstName)).sendKeys("Test");
FileUtils.copyFile(scrFile, new File("./ScreenShots/"));
driver.findElement(By.id(StringsDj.lastName)).sendKeys("Dj");
FileUtils.copyFile(scrFile, new File("./ScreenShots/"));
driver.findElement(By.id(StringsDj.emailId)).sendKeys("reachdipanjan#gmail.com");
FileUtils.copyFile(scrFile, new File("./ScreenShots/"));
driver.findElement(By.id(StringsDj.password)).sendKeys("TestDj");
FileUtils.copyFile(scrFile, new File("./ScreenShots/"));
}
#Then("^I should see error$")
public void i_should_see_error() throws Throwable
{
System.out.println("error displayed");
}
}
The error received:
cucumber.runtime.CucumberException: Failed to instantiate class AppiumdemoDj.SignUpDj
at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:47)
at cucumber.runtime.java.DefaultJavaObjectFactory.getInstance(DefaultJavaObjectFactory.java:33)
at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
at cucumber.runtime.Runtime.runStep(Runtime.java:300)
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.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.reflect.InvocationTargetException
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 cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:41)
... 32 more
Caused by: java.lang.NullPointerException
at AppiumdemoDj.SignUpDj.<init>(SignUpDj.java:25)
... 37 more
The driver object is null on the line 25 of the SignUpDj class because it has not been initialized:
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Taking screenshot
You need to invoke that code whenever you want to take a screenshot, not on the class initialization. I am not sure what you are trying to achieve with the code below:
FileUtils.copyFile(scrFile, new File("./ScreenShots/"));
But this will not take a screenshot. You need to wrap up the call to take a screenshot in a method and call that method instead.
here is my junit which i am trying to implement.
import static org.mockito.Mockito.when;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class Power_Test {
#InjectMocks
ReportUtil w_res = new ReportUtil();
CollectionUtil mock = org.mockito.Mockito.mock(CollectionUtil.class);
#Test
public void test_removeHashedSettings() throws Exception {
HashMap<String, String> w_abc = new HashMap<String, String>();
w_abc.put("abc", "89");
when(mock.createHashMap("abc:89",":")).thenReturn(w_abc);
Assert.assertEquals(ReportUtil.removeHashedSettings("1", "abc:89", ":"),"abc:89:",0);
}
}
I want to mock createHashMap() method which is static method.
Below is an error trace which i am getting while running the above junit.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods cannot be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.de.base.util.general.Power_Test.test_removeHashedSettings(Power_Test.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
please help.
here is createHashMap Api
public static HashMap<String, String> createHashMap(String a_NameValStr, String a_Delim)
{
HashMap<String, String> w_KeyVal = new HashMap<String, String>();
if (LOGGER.isInfoEnabled()) LOGGER.info("CollectionUtil:createHashMap:Hashing string: "+ a_NameValStr );
if(a_NameValStr == null) return w_KeyVal;
StringTokenizer w_StrTkn = new StringTokenizer(a_NameValStr, a_Delim);
if( w_StrTkn.countTokens() == 0 || (w_StrTkn.countTokens()%2) != 0 )
{
LOGGER.warn("CollectionUtil:createHashMap:Invalid number of tokens to hash: "+ a_NameValStr+":"+w_StrTkn.countTokens() );
return w_KeyVal;
}
while (w_StrTkn.hasMoreTokens()) w_KeyVal.put( w_StrTkn.nextToken(), w_StrTkn.nextToken());
return w_KeyVal;
}
I looked around and am a little confused if it is working or not. The result while debugging gives me the impression that it fails.
Statement 'throw new SessionTimeoutException("Session Timeout"); ' not supported
I am running a test case in Junit and have made many using exceptions previously already however they are implemented in the same manner as the method below at.
private void checkSessionTimeout(HtmlPage page) throws SessionTimeoutException {
I am new to Exceptions and do not understand why it only errors at runtime during the test.
My test runs and fails in the method inside the if statement
private void checkSessionTimeout(HtmlPage page) throws SessionTimeoutException {
HtmlDivision imgDivElement = page.getFirstByXPath("//div[#class='border']");
HtmlDivision errorDivElement = page.getFirstByXPath("//div[#class='error']");
String imgUrl = imgDivElement.getFirstElementChild().getAttribute("src");
String errorMessage = errorDivElement.getTextContent().trim();
if(page.getWebResponse().getContentAsString().contains(imgUrl) && page.getWebResponse().getContentAsString().contains(errorMessage)){
throw new SessionTimeoutException("Session Timeout");
}
}
At this line: throw new SessionTimeoutException("Session Timeout");
package com.cantShow;
import com.cantShow.htmlunit.html.HtmlPage;
import com.cantShow.TimeoutInformation;
import com.cantShow.AbstractScraperTest;
import com.cantShow.scrape.Scraper;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.cantShow.SessionTimeoutException;
public class ScraperTest extends ScraperTest<HtmlPage, SessionTimoutClassWithGettersSetters> {
#Override
protected Scraper<HtmlPage, SessionTimoutClassWithGettersSetters> getScraper() {
return new Scraper();
}
#Test
public void scrape() throws Exception {
SessionTimoutClassWithGettersSettersresult = testScraper("/scrape/timeout-session.html",
"https://cantShow.html");
details(result, "imgs/error.png","Your session has timed out. You will need to log back in to continue shopping.");
}
private static void details(SessionTimoutClassWithGettersS setterstimeoutInformation, String errorImgUrl, String errorMsg){
assertEquals(errorImgUrl, sessionTimoutClassWithGettersSetters.getErrorImageUrl());
assertEquals(errorMsg, sessionTimoutClassWithGettersSetters.getErrorMessage());
}
}
Stack Trace:
com.cantShow.Scraper.checkSessionTimeout(Scraper.java:28)
atcom.cantShow.Scraper.Scraper.scrape(Scraper.java:16)
at com.cantShow.Scraper.Scraper.scrape(Scraper.j va:12)
at com.cantShow.Scraper.ScrapeService.scrapeString(ScrapeService.java:406)
at com.cantShow.Scraper.AbstractScraperTest.testScraper(AbstractScraperTest.java:32)
at com.cantShow.Scraper.ScraperTest.scrape(ScraperTest.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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I have looked at other posts on Stack Overflow however could not find one like this for Java.
If you want to test that the Exception is thrown you have to catch it and verify that it is the right Exception.
#Test
public void scrape() throws Exception {
boolean exceptionHappend = false;
try {
SessionTimoutClassWithGettersSettersresult =
testScraper("/scrape/timeoutsession.html", "https://cantShow.html");
} catch (SessionTimeoutException e) {
exceptionHappend = true;
}
assertTrue(exceptionHappend);
details(result, "imgs/error.png","Your session has timed out. You will need to log back in to continue shopping.");
}