Selenium-TestNG-Maven - Getting "java.lang.NoClassDefFoundError: org/openqa/selenium/firefox/FirefoxDriver" - maven

This is my first selenium script using TestNG and Maven.
Created a simple "Hello World" code and a selenium test code which just checks the title of google page.
Selenium Code Below with TestNG:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class HelloTest {
#Test
public void testOne() {
//WebDriver d=new FirefoxDriver();
System.setProperty("webdriver.gecko.driver","D:\\Firefox Driver\\geckodriver-v0.17.0-win64\\geckodriver.exe");
WebDriver d=new FirefoxDriver();
d.get("https://www.google.com");
System.out.println("This is first TestNG");
}
}
This is working absolutely fine when run through eclipse - Run As - Test NG test.
But when ran through Maven - mvn clean install from cmd prompt, i am getting below error
T E S T S
-------------------------------------------------------
Running HelloTest
Configuring TestNG with: TestNG652Configurator
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.94 sec <<< FAILURE! - in HelloTest
testOne(HelloTest) Time elapsed: 0.032 sec <<< FAILURE!
java.lang.NoClassDefFoundError: org/openqa/selenium/firefox/FirefoxDriver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at HelloTest.testOne(HelloTest.java:11)
It is showing error at WebDriver d=new FirefoxDriver();. Not sure where the issue is. Added all jar files , checked the build path and all the jar were there. Below is my POM file.
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.micky</groupId>
<artifactId>MavenDemoTwo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<type>jar</type>
<version>15.0</version>
</dependency>
</dependencies>
</project>
Any help is deeply appreciated.

What is NoClassDefFoundError
NoClassDefFoundError in Java occurs when JVM is not able to find a particular class at runtime which was available at compile time. For example, if we have resolved a method call from a Class or accessing any static member of a Class and that Class is not available during runtime then JVM will throw NoClassDefFoundError.
The error you are seeing is :
java.lang.NoClassDefFoundError: org/openqa/selenium/firefox/FirefoxDriver
This clearly indicates that Selenium is trying to resolve the particular FirefoxDriver Class at runtime from org/openqa/selenium/firefox/FirefoxDriver which is not available.
What went wrong :
This situation occurs if there are presence of multiple sources to resolve the Classes and Methods through JDK/Maven/Gradle.
From the pom.xml it is pretty clear that you have added multiple dependencies for FirefoxDriver Class as follows:
<artifactId>selenium-java</artifactId>:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.12.0</version>
<scope>test</scope>
</dependency>
<artifactId>selenium-firefox-driver</artifactId>:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.12.0</version>
</dependency>
<artifactId>selenium-server</artifactId>:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.12.0</version>
</dependency>
Additionally you have also added all jar files.
From all the above mentioned points it's clear that the related Class or Methods were resolved from one source at Compile Time which was not available during Run Time.
Solution :
Here are a few steps to solve NoClassDefFoundError :
While using a Build Tool e.g. Maven or Gradle, remove all the External JARs from the Java Build Path. Maven or Gradle will download all the dependencies mentioned in the configuration file (e.g. pom.xml) to resolve the Classes and Methods.
If using Selenium JARs within a Java Project add only required External JARs within the Java Build Path and remove the unused and duplicate External JARs.
If you are using FirefoxDriver use either of the <artifactId>selenium-java</artifactId> or <artifactId>selenium-server</artifactId>. Avoid using both at the same time.
Remove the unwanted and duplicated from pom.xml
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
Use CCleaner tool to wipe off all the OS chores before and after the execution of your Test Suite.
If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.
Take a System Reboot.
While you execute a Maven Project always perform the folling in sequence:
maven clean
maven install
maven test
You can find related discussions in:
Exception in thread “main” java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
How to solve java.lang.NoClassDefFoundError? Selenium
java.lang.NoClassDefFoundError: com/google/common/base/Function

I was using eclipse 09-2019 which is the latest one with latest JDK installed 13, and latest selenium jar files 3.141.59, I installed other JDKs to work around to solve this issue after trying all answers on similar question. Then after 4 days trying, installed eclipse neon version(https://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/neon/3/eclipse-java-neon-3-win32-x86_64.zip&mirror_id=105) and used Selenium-Java 3.5.2 jar files (https://jar-download.com/artifacts/org.seleniumhq.selenium/selenium-java/3.5.2/source-code) and now it is working perfectly Alhamdullilah.
Also I don't know what was the errors root cause exactly or at all, but now it is solved.
Wish if that help You

Related

Liquibase fails with MongoDB

I want to get an example of liquibase, Spring and MongoDB all together. In order to do so, I created a Spring project using Spring Initializr with Spring Data MongoDB as dependency. The project already connects to the database and now I would like to use liquibase. I followed the instructions from liquibase using the maven approach but if I run the maven command mvn liquibase:status I will get the following error:
Unexpected error running Liquibase: Cannot find database driver: com.mongodb.client.MongoClients.<init>()
It looks like this problem has been already reported to liquibase but if there is a solution it hasn't been posted in the issue.
I tried as well to use the CLI option by adding the jars to the lib folder of the liquibase installation. I got the same error if I run liquibase status
I have created a repo in GitHub to show the problem. Here there is some relevant configuration of the code:
pom.xml
<project>
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
...
<properties>
<liquibase-mongo-ext.version>4.14.0</liquibase-mongo-ext.version>
<liquibase-maven-plugin.version>4.2.0</liquibase-maven-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.liquibase.ext</groupId>
<artifactId>liquibase-mongodb</artifactId>
<version>${liquibase-mongo-ext.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>${liquibase-maven-plugin.version}</version>
<configuration>
<propertyFile>liquibase.properties</propertyFile>
</configuration>
<dependencies>
<dependency>
<groupId>org.liquibase.ext</groupId>
<artifactId>liquibase-mongodb</artifactId>
<version>${liquibase-mongo-ext.version}</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.6.1</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
liquibase.properties
changeLogFile=./mongo/changelog/changelog.sql
url=jdbc:mongodb://127.0.0.1:27017/local
driver=com.mongodb.client.MongoClients
How can I get liquibase running with maven? Any suggestions?
EDIT 1:
As Andrey suggested:
Driver was updated to: driver=liquibase.ext.mongodb.database.MongoClientDriver
Url was updated to:
url=mongodb://127.0.0.1:27017/local
plugin from liquibase was updated with new dependency
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
</dependency>
mvn liquibase:update now trhows the following error. Since the other error seems to be unrelated to this one. I'll solve this answer and create a new thread.
[ERROR] Failed to execute goal org.liquibase:liquibase-maven-plugin:4.2.0:update (default-cli) on project mongo: Execution default-cli of goal org.liquibase:liquibase-maven-plugin:4.2.0:update failed: A required class was missing while executing org.liquibase:liquibase-maven-plugin:4.2.0:update: liquibase/configuration/HubConfiguration
EDIT 2:
As mentioned in the answer, there was a mismatch between the version from Spring and the version of the plugin, which failed to find the class because HubConfiguration class is now under liquibase.hub.HubConfiguration This set up could have led to a CastException as well. So I updated the version liquibase-maven-plugin to 4.9.1
Also the use of the local database is not compatible with validators. The URI was updated to url=mongodb://127.0.0.1:27017/test in the liquibase.properties file.
Now it works like a charm! :D
I have found following mistakes in your configuration:
1.
changeLogFile=./mongo/changelog/changelog.sql
url=jdbc:mongodb://127.0.0.1:27017/local
driver=com.mongodb.client.MongoClients
while liquibase-mongodb expects something like (no jdbc prefix, another driver class):
changeLogFile=./mongo/changelog/changelog.sql
url=mongodb://127.0.0.1:27017/local
driver=liquibase.ext.mongodb.database.MongoClientDriver
liquibase version:
<liquibase-maven-plugin.version>4.2.0</liquibase-maven-plugin.version>
4.2.0 liquibase version seems to be incompatible with NoSQL DB extensions
spring boot 2.7.3 uses liquibase 4.9.1 - you need somehow choose the correct liquibase version
Finally I get the following on liquibase:update:
[ERROR] Failed to execute goal
org.liquibase:liquibase-maven-plugin:4.14.0:update (default-cli) on
project mongo: [ERROR] Error setting up or running Liquibase: [ERROR]
liquibase.exception.DatabaseException: Could not execute: Command
failed with error 72 (InvalidOptions): 'Document validators are not
allowed on collection local.DATABASECHANGELOGLOCK with UUID
31bd40b8-3e1c-45c8-9d03-77b91c67a1a9 in the local internal database'
on server 127.0.0.1:27017. The full response is {"ok": 0.0, "errmsg":
"Document validators are not allowed on collection
local.DATABASECHANGELOGLOCK with UUID
31bd40b8-3e1c-45c8-9d03-77b91c67a1a9 in the local internal database",
"code": 72, "codeName": "InvalidOptions"}
no idea what does it mean - something related to mongodb and extension I believe
UPD.
The root cause of last error is described in documentation:
Restrictions
You cannot specify a validator for collections in the admin, local, and config databases.
You cannot specify a validator for system.* collections.
So, url (jdbc:mongodb://127.0.0.1:27017/local) should point to another db.

Mockito cannot mock this class: interface

I'm having an issue with mockito and powermock, I can mock an abstract class with a final static method with no problems. When trying to mock an Interface as with WebIServerSession I'm getting the stacktrace below. I've had a look at other issues in powermock github repo and it seems to be related with the jvm version. I've already upgraded to the latest 1.8 java version as stated in https://github.com/mockito/mockito/issues/636 and I'm still getting the same error. Might it be related with Powermock compatibility with Mockito 2?
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
#BeforeMethod
public void setup() throws Exception {
mockStatic(ResourceBundle.class);
mockStatic(WebObjectsFactory.class);
WebObjectsFactory webObjectsFactory = mock(WebObjectsFactory.class);
WebIServerSession webIServerSession = mock(WebIServerSession.class);
PowerMockito.when(WebObjectsFactory.getInstance()).thenReturn(webObjectsFactory);
PowerMockito.when(webObjectsFactory.getIServerSession()).thenReturn(webIServerSession);
whenNew(ThreadLocal.class).withNoArguments().thenReturn(errorContainer);
MockitoAnnotations.initMocks(this);
}
#Test
public void shouldBeTrue() {
assertTrue(true);
}
Maven dependencies:
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
</dependencies>
Stacktrace:
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.microstrategy.web.objects.WebIServerSession.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 1.8
JVM vendor name : Oracle Corporation
JVM vendor version : 25.191-b12
JVM name : Java HotSpot(TM) 64-Bit Server VM
JVM version : 1.8.0_191-b12
JVM info : mixed mode
OS name : Mac OS X
OS version : 10.14.1
Underlying exception : java.lang.IllegalArgumentException: Could not create type
at com.myproject.SSOESMTest.setup(SSOESMTest.java:63)
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:124)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Could not create type
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
... 28 more
Caused by: java.lang.NoClassDefFoundError: com/microstrategy/utils/xml/SAXSupport
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8426)
at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3654)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:463)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:189)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3394)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3583)
at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
... 39 more
Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupport
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 63 more
Test ignored.
===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 2
===============================================
Process finished with exit code 0
The exception is most likely to occur due to the version of Mockito used.
Try by replacing the current version of mockito-core with below dependency.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.22.0</version>
<scope>test</scope>
</dependency>
Ignore the warning of overriding managed version in pom.xml
Make sure your interface visibility is public.
I am not sure that it will be the solution in your case. I got the same issue when I was testing in Android Studio.
My solution was replace core-mockito with
androidTestImplementation "org.mockito:mockito-android:2.25.0"
Then it started working perfect.
It may be solution for those who are testing for Android Studio and having the same issue.
add
#RunWith(MockitoJUnitRunner.class)
I also experienced this problem when trying to mock a non-public interface, and the error message didn't make sense, as all my tests in another suite passed correctly while mocking the same interface.
In my case I had to downgrade the Mockito Core library and revert it again to make it work. Here are the steps I took:
Find the Mockito Core dependency in the module level build.gradle file entry:
testImplementation 'org.mockito:mockito-core:2.25.0'
Downgrade to another valid version, in my example 2.23.0:
testImplementation 'org.mockito:mockito-core:2.23.0'
Do a Gradle sync and wait for completion
Revert the Mockito Core dependency to the same version you had before (or newer):
testImplementation 'org.mockito:mockito-core:2.25.0'
Sync the project again
Run the tests again
I had a similar issue. I was surprisingly having:
Mockito cannot mock this class: interface javax.servlet.ServletContext.
This was only when I ran my test in my IDE (IntelliJ Idea). If I tried to run it via maven command - it passed.
To make the test work in IntelliJ Idea I just changed the configurations:
Set Shorten command line to JAR manifest.
It's Strange but after adding below line in build.gradle file it work for me
androidTestImplementation "org.mockito:mockito-android:$mockitoAndroid"
I also have this problem by using IDEA, finally choose Shorten command line: "JAR manifest" solved
annotate your test class like this
#RunWith(PowerMockRunner.class)
#PrepareForTest({ResourceBundle.class, WebObjectsFactory.class, AnyOtherClassThatContainsStaticMethod.class, . . .})
ref: https://github.com/powermock/powermock/wiki/mockstatic

Elasticsearch Java API from web application-error: java.lang.NoClassDefFoundError: Could not initialize class org.elasticsearch.threadpool.ThreadPool

I couldn't use elasticsearch Java API through JSP. In the following, I have tried to explain what I have done. :|
I have installed elasticseach 2.3.3 on my system by following the elastic instruction and run it from command prompt. everything is working perfectly. It may be useful to say, I have changed below parameters from elasticsearch.yml.
cluster.name: cluster_233
node.name: node_233
bootstrap.mlockall: true
network.host: 127.0.0.1
Then with Netbeans, I have created a Maven project -> Web application project and set the below dependency in pom.xml :
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
<type>jar</type>
</dependency>
Also I have added the Guava version 18 dependency into project and then download all the project dependencies by right clicking on Dependencies and select Download Declared Dependencies . Then created a java class and write below code:
package com.mycompany.esmaven;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
public class aClass {
public String test() throws Exception {
String str = tryToIndex();
String dfd = "";
return str;
}
public String tryToIndex() throws Exception {
Node node = NodeBuilder.nodeBuilder().settings(
Settings.builder()
.put("path.home", "d:/elasticsearch-2.3.3")
.put("cluster.home", "cluster_233")
).node();
Client client = node.client();
client.prepareIndex("kodcucom", "article", "1")
.setSource(putJsonDocument("ElasticSearch: Java API",
"ElasticSearch provides the Java API, all operations "
+ "can be executed asynchronously using a client object.",
new Date(),
new String[]{"elasticsearch"},
"Hüseyin Akdoğan")).execute().actionGet();
node.close();
return "Done";
}
public static Map<String, Object> putJsonDocument(String title,
String content, Date postDate, String[] tags, String author) {
Map<String, Object> jsonDocument = new HashMap<String, Object>();
jsonDocument.put("title", title);
jsonDocument.put("conten", content);
jsonDocument.put("postDate", postDate);
jsonDocument.put("tags", tags);
jsonDocument.put("author", author);
return jsonDocument;
}
}
And through a jsp page tried to call the test() function (I'm going to integrate elasticsearch with a web application). Always after building the project at the first load the below error will appear:
java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
and after refreshing the page the context of error will change to:
java.lang.NoClassDefFoundError: Could not initialize class org.elasticsearch.threadpool.ThreadPool
This is the POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ISTEX</groupId>
<artifactId>mvnESwebapp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mvnESwebapp</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Also, I would like to mention, with this POM I can index my JSON from the main function. But the problem is I did not know how to run the application through JSP pages.
I really appreciate you for sharing your knowledge.
Regards,
Amin
FWIW, I ran into the same issue as described above -- that is, the error message I saw was the threadpool initialization error the author describes. The solution described in the link below solved the problem for me:
https://discuss.elastic.co/t/could-not-initialize-class-org-elasticsearch-threadpool-threadpool/47575
UPDATED per comment suggestion:
In my case, the fix was to add a guava dependency entry in my POM file. I used the dependency given in the webpage at the link above:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
That, at least in my case, solved the problem.
With Java applications, errors like
java.lang.NoSuchMethodError
java.lang.NoClassDefFoundError
generally indicate that you are missing a dependency or you have conflicting dependency. For example, Guava 18.0 and Guava 19.0 are completely different as far as Java is concerned, but they share a lot of code. As the jars are loaded, one will naturally be loaded first, so any attempted usage of the second will cause misleading errors like those above.
Also I have added the Guava version 18 dependency into project and then download all the project dependencies by right clicking on Dependencies and select Download Declared Dependencies
Elasticsearch 2.3.3 already depends on Guava 18.0. As such, it's a transitive dependency of the Elasticsearch project.
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
<type>jar</type>
</dependency>
Your Maven dependency is probably creating a collision with one of your other dependencies. Take a look at your Netbeans dependencies, or more appropriately ask Maven to do it directly:
mvn dependency:tree -Dverbose
This will print out the dependency tree for you to find conflicts. Look for jars that are duplicated with different versions and stop the mismatch from happening.
As a side note, at the time of this answer, Guava 19 is the latest version. So even though ES 2.3.3 wants Guava 18, some other dependency of yours could easily and reasonably want a different version of Guava.

Servlet 500 error ClassNotFound exception

I'm building a web app using Vaadin and it needs to communicate with several REST APIs. I've set it up in IntelliJ with Maven. I was thinking for the REST client I would use GSON to parse the JSON objects I'd be receiving from the open APIs, however, the application crashes due to a servlet exception error.
Caused by:
java.lang.ClassNotFoundException: com.google.gwt.json.client.JSONObject
I've added the GSON dependency to the pom.xml:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
And have tried changing the module settings from Provided to Compiled to Runtime but with no change.
I'm just stumped as to why the GSON jar appears in the project dependencies within IntelliJ using Maven but fails on run time. I've seen references to Eclipse and including the jar in the classpath but, again, I'm using IntelliJ/Maven to build my Vaadin project and satisfy dependencies.
Any help is greatly appreciated!
Add below dependency in your classpath:
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>2.3.0</version>
</dependency>

Glassfish incremental deployment failes when including Selenium

I have a Java EE project which is meant to run on Glassfish 4.1. I want to use Selenium to collect information from some web pages, i.e. I need to include Selenium in the deployment (not just for tests).
I am using Eclipse IDE and have previously utilized the incremental deployment function in Eclipse to automatically deploy all saved changes to the project. But when I included (with Maven) the dependencies for Selenium incremental deployment stopped working. The project can still be deployed to Glassfish but I have to restart Glassfish between every change. I get the following error in Eclipse:
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: java.util.concurrent.ExecutionException: com.sun.faces.config.ConfigurationException: Unable to parse document 'bundle://136.0:1/com/sun/faces/jsf-ri-runtime.xml': DTD factory class org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl does not extend from DTDDVFactory.. Please see server.log for more details.
org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl is included with Selenium as a transitive dependency (xerces:xercesImpl:2.11.0).
Here are my Maven dependencies:
<dependency>
<groupId>org.jboss.arquillian.selenium</groupId>
<artifactId>selenium-bom</artifactId>
<version>2.44.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
</dependency>
I hope there is a solution to this but after reading Jens Schauder's response in Dealing with "Xerces hell" in Java/Maven? I'm afraid there might not be. Anyone?
I currently can't reproduce the issue with a simple project, did you make sure that you don't have any other dependencies which are importing another version of xercesImpl?
You can try to place the xercesImpl-2.11.0.jar and the transitive dependency xml-apis-1.4.01.jar in the lib folder of your Glassfish domain and exclude it from your dependencies like this:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
<version>2.44.0</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency>
See also:
org.apache.xerces.impl.dv.DVFactoryException: DTD factory class org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl does not extend from DTDDVFactory
Xerces error: org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl

Resources