草庐IT

java - org.glassfish.jersey.server.ContainerException : java. lang.NoClassDefFoundError : org. testng.TestNG?

coder 2024-04-01 原文

我在 Eclipse 中有一个项目,它是一个 WebService 项目 REST API,我还在 Configure Build path -> Add Project 中添加了另一个项目,我还添加了另一个项目在我的 API 方法中,我正在调用 TestNGCreator 类,如下所示。

基本上这个项目使用 java 中的 jersey 框架来创建 REST API,当我调用任何特定方法时,即执行它将调用另一个驻留在另一个项目中的类,我在这个项目的构建路径中添加了项目,我的其他方法工作正常但是当我从不同的项目调用方法时出现此错误。

我是否需要在 POM.xml 或其他地方声明一些我正在使用此类和此方法的地方

我需要通过调用此 TestNGCreator.main(null); 来运行自动化 我的另一个项目是 java 中的自动化项目 TestNGCreator 类驻留在自动化项目中。通过调用此方法,我需要调用上面的类,当我这样做时出现错误。

错误:

    May 17, 2019 4:20:51 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/webservices] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/testng/TestNG] with root cause
java.lang.ClassNotFoundException: org.testng.TestNG
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1955)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1798)
    at testDrivers.TestNGCreator.runTestNGTest(TestNGCreator.java:44)
    at testDrivers.TestNGCreator.main(TestNGCreator.java:165)
    at com.xyz.webservices.Resource.executeScript(Resource.java:179)
    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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:143)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:160)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:158)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:97)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:303)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1072)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:399)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1137)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:317)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

文件:Resource.java

      @POST
      @Path("/execute")
      @Consumes(MediaType.APPLICATION_JSON)
      @Produces(MediaType.APPLICATION_JSON)
      public Response executeScript(String data) throws JSONException
        {   
            ArrayList<Object> testCases = new ArrayList<Object>();
            JSONArray jsonArray = new JSONArray();
            JSONObject json = new JSONObject(data);
            String configFile = (String) json.get("ConfigFiles");
            String sheetName = (String) json.get("Sheetname");
            jsonArray = (JSONArray) json.get("testCases");

            for (int i = 0 ; i < jsonArray.length() ; i++)
            {
                testCases.add(jsonArray.get(i));
            }

            try {
                TestNGCreator.main(null); //here  i am calling that class main method
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Response response = null;
            System.out.println(jsonArray);
            System.out.println(testCases);
            return response;
        }

文件:TestNGCreator.java

package testDrivers;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;

import projlib.Globals;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;




public class TestNGCreator 
{

    public void runTestNGTest() throws IOException 
    {

            System.out.println("Print this line in console");
            //Create an instance on TestNG
            TestNG myTestNG = new TestNG();

            //Create an instance of XML Suite and assign a name for it.
            XmlSuite mySuite = new XmlSuite();
            mySuite.setName(Globals.SUITE_NAME);

            //Create a list of XmlTests and add the Xmltest you created earlier to it.
            List<XmlTest> myTests = new ArrayList<XmlTest>();

            XSSFSheet excelWSheet = null;
            XSSFWorkbook excelWBook = null;
            XSSFCell cell = null;
            XSSFRow row = null;

            Double dblCellVal;
            String strCellVal = null;
            Boolean blnCellVal;

            FileInputStream excelFile = new FileInputStream(Globals.CONFIG_FILE_DIR+"/CropRecordConfig.xlsx");
            excelWBook = new XSSFWorkbook(excelFile);
            excelWSheet = excelWBook.getSheet("CropAdd");


            Iterator <Row> rowIterator = excelWSheet.iterator(); 
            //Iterator <Cell> cellIterator = row.cellIterator();
            String testName = null;
            int colCount;

            if (rowIterator.hasNext())
            {
                row = (XSSFRow) rowIterator.next();
                colCount = row.getPhysicalNumberOfCells();
            }
            while (rowIterator.hasNext())
            {
                row = (XSSFRow) rowIterator.next();
                Iterator <Cell> cellIterator = row.cellIterator();
                int curCell = 0;
                while (cellIterator.hasNext())
                {
                    cell = (XSSFCell) cellIterator.next();
                    curCell++;
                    switch (cell.getCellType())
                    {
                    case Cell.CELL_TYPE_NUMERIC:
                        dblCellVal = cell.getNumericCellValue();
                        strCellVal = dblCellVal.toString();
                        break;
                    case Cell.CELL_TYPE_STRING:
                        strCellVal = cell.getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        blnCellVal = cell.getBooleanCellValue();
                        strCellVal = blnCellVal.toString();
                        break;
                    }

                    //If it is first cell then store the Test Name
                    if (cell.getColumnIndex()== 0)
                    {
                        testName = strCellVal;
                    }

                    if (curCell == 5) {
                        if (strCellVal.equals("1.0")) {
                            //Adding to suite
                            //Create an instance of XmlTest and assign a name for it.
                            XmlTest myTest = new XmlTest(mySuite);
                            myTest.setName(testName);

                            //Add any parameters that you want to set to the Test.
                            Map<String, String> testngParams = new HashMap<String,String> ();
                            testngParams.put("testId", testName);
                            myTest.setParameters(testngParams);

                            //Create a list which can contain the classes that you want to run.
                            List<XmlClass> myClasses = new ArrayList<XmlClass> ();
                            myClasses.add(new XmlClass("TestDriver"));

                            //Assign that to the XmlTest Object created earlier.
                            myTest.setXmlClasses(myClasses);

                            //Adding the test to test list created earlier
                            myTests.add(myTest);
                            break;

                        }
                    }
                }

            }

            excelWBook.close();

            //add the list of tests to your Suite.
            mySuite.setTests(myTests);

            //Add the suite to the list of suites.
            List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
            mySuites.add(mySuite);

            //Set the list of Suites to the testNG object you created earlier.
            myTestNG.setXmlSuites(mySuites);

            File file = new File(Globals.TESTNG_FILE_NAME);
            System.out.println("File is: " + file);

            FileWriter writer = new FileWriter(file);
            writer.write(mySuite.toXml());
            writer.close();

            //invoke run() - this will run your class.
            //myTestNG.run();




    }
    public static void main(String args[]) throws IOException
    {
        TestNGCreator testDriver = new TestNGCreator();
        testDriver.runTestNGTest();
    }
}

文件:POM.xml

<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xyz</groupId>
    <artifactId>webservices</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>webservices</name>

    <build>
        <finalName>webservices</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
        </dependency>
        <!-- uncomment this to get JSON support-->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
             <version>20080701</version>
       </dependency>
         <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.15</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.15</version>
    </dependency>
    </dependencies>

    <properties>
        <jersey.version>2.16</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

如有任何建议,我们将不胜感激^.^

最佳答案

我在你的 pom 文件中没有看到 test-ng 依赖项。 请添加以下内容并尝试。

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.10</version>
    <scope>test</scope>
</dependency>

关于java - org.glassfish.jersey.server.ContainerException : java. lang.NoClassDefFoundError : org. testng.TestNG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148031/

有关java - org.glassfish.jersey.server.ContainerException : java. lang.NoClassDefFoundError : org. testng.TestNG?的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  4. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  5. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  6. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  7. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  8. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  9. java - 为什么 ruby​​ modulo 与 java/other lang 不同? - 2

    我基本上来自Java背景并且努力理解Ruby中的模运算。(5%3)(-5%3)(5%-3)(-5%-3)Java中的上述操作产生,2个-22个-2但在Ruby中,相同的表达式会产生21个-1-2.Ruby在逻辑上有多擅长这个?模块操作在Ruby中是如何实现的?如果将同一个操作定义为一个web服务,两个服务如何匹配逻辑。 最佳答案 在Java中,模运算的结果与被除数的符号相同。在Ruby中,它与除数的符号相同。remainder()在Ruby中与被除数的符号相同。您可能还想引用modulooperation.

  10. java - Ruby 相当于 Java 的 Collections.unmodifiableList 和 Collections.unmodifiableMap - 2

    Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur

随机推荐