当前位置: 首页 > 知识库问答 >
问题:

java.lang.VerifyError在为maven项目运行JUNIT mockito和power mock时

柴赞
2023-03-14

当我运行clean cobertura:cobertura时,这是一个例外。我试着从eclipse中运行JUNIT,但仍然没有成功
我正在为我的项目使用以下依赖项。

  • org.mockitomockito-all 1.10.19
  • org.mockitomockito-core 1.10.19
  • jUnit 4.11
  • junit-addons junit-addons 1.4
  • org.powermockpower mock模块
  • org.powermockpower mock-api-mockito 1.6.2

POM文件更改:

<cobertura-maven-plugin.version>2.6</cobertura-maven-plugin.version>
<maven-surefire-plugin.version>2.12.2</maven-surefire-plugin.version>
            <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>cobertura-maven-plugin</artifactId>
                    <version>${cobertura-maven-plugin.version}</version>
                    <configuration>
                        <formats>
                            <!-- Comment out any output formats you dont need (will put in a profile later) -->
                            <format>html</format>       
                            <!-- <format>xml</format>-->
                        </formats>
                        <outputDirectory>${project.build.directory}/coverage-reports</outputDirectory>      
                        <!-- <instrumentation>
                            <ignoreTrivial>true</ignoreTrivial>         
                            <ignores>
                                <ignore>org.slf4j.Logger.*</ignore>     
                            </ignores>
                            <excludes>
                                <exclude>**/Example.class</exclude>     
                            </excludes>
                        </instrumentation> -->
                    </configuration>
                    <executions>
                        <!-- <execution>
                            <id>clean-coverage-report</id>
                            <phase>clean</phase>            
                            <goals>
                                <goal>clean</goal>
                            </goals>
                        </execution> -->
                        <execution>
                            <id>create-coverage-report</id>
                            <phase>package</phase>          
                            <goals>
                                <goal>cobertura</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${maven-surefire-plugin.version}</version>
                    <configuration>
                        <skipTests>false</skipTests>
                        <testFailureIgnore>true</testFailureIgnore>
                        <forkMode>once</forkMode>
                        <argLine>-Xms512m -Xmx1024m -XX:MaxPermSize=512m</argLine>
                    </configuration>
                </plugin>
                <!-- test dependencies -->
            <!-- Mocking & Testing Code -->
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
                <version>1.10.19</version>
            </dependency>
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
                <version>1.10.19</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>junit-addons</groupId>
                <artifactId>junit-addons</artifactId>
                <version>1.4</version>
            </dependency>   
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-module-junit4</artifactId>
                <version>1.6.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-api-mockito</artifactId>
                <version>1.6.2</version>
                <scope>test</scope>
            </dependency>

例外:

java.lang.VerifyError: (class: com/day/cq/search/Predicate, method: <init> signature: (Ljava/lang/String;Ljava/lang/String;)V) Constructor must call super() or this()
            at java.lang.Class.getDeclaredConstructors0(Native Method)
            at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
            at java.lang.Class.getDeclaredConstructors(Unknown Source)
            at org.powermock.api.mockito.repackaged.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:85)
            at org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:71)
            at org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:49)
            at org.powermock.api.mockito.repackaged.CglibMockMaker.createMock(CglibMockMaker.java:24)
            at org.powermock.api.mockito.internal.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:45)
            at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
            at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
            at org.mockito.Mockito.mock(Mockito.java:1285)
            at org.mockito.Mockito.mock(Mockito.java:1163)
            at com.ftc.digital.services.search.impl.SearchServiceImplTest.setUp(SearchServiceImplTest.java:62)
            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.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.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:106)
            at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
            at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
            at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
            at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
            at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
            at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
            at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
            at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

更新:搜索类别代码:

@Service(SearchService.class)
@Component(label = "Search Service", metatype = true, immediate = true)
public class SearchServiceImpl implements SearchService
{
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public final SearchResult getResult(final SlingHttpServletRequest slingRequest, final Map<String,
         String> predicateParameterMap, final String searchRootPath, final int startPage, final int resultsPerPage)
    {
        // Add additional predicates
        logger.info("resultsPerPage" + resultsPerPage);
        predicateParameterMap.put("path", searchRootPath);
        predicateParameterMap.put("p.offset", Long.toString(calculateOffset(startPage, resultsPerPage)));
        predicateParameterMap.put("p.limit", Integer.toString(resultsPerPage));
        predicateParameterMap.put("orderby", "@jcr:score");
        predicateParameterMap.put("orderby.sort", "desc");

        // Create query and get result
        final com.day.cq.search.result.SearchResult result = createQuery(slingRequest.getResourceResolver(),
                predicateParameterMap).getResult();

        // Populate search result
        final SearchResult searchResult = new SearchResult();
        searchResult.setCurrentPage(calculateCurrentPage(result.getStartIndex(), result.getHitsPerPage()));
        searchResult.setTotalPages(calculateTotalPages(result.getTotalMatches(), result.getHitsPerPage()));
        searchResult.setTotalResults(result.getTotalMatches());
        searchResult.setResultsPerPage((int) result.getHitsPerPage());
        searchResult.setResults(result.getHits());
        return searchResult;
    }

    @Override
    public final long calculateOffset(final int startPage, final int resultsPerPage)
    {
        if (startPage <= 1)
        {
            return 0;
        }

        return ((startPage * resultsPerPage) - resultsPerPage);
    }

    /**
     * Calculates the current page number.
     * 
     * @param startIndex The start index of the search results.
     * @param hitsPerPage The results to show per page.
     * @return The calculated current page number.
     */
    private int calculateCurrentPage(final long startIndex, final long hitsPerPage)
    {
        if (startIndex == 0L)
        {
            return 1;
        }

        return (int) Math.ceil((double) (startIndex + 1) / hitsPerPage);
    }

    /**
     * Calculates the total pages for the search results.
     * 
     * @param totalMatches The total search results.
     * @param hitsPerPage The results to show per page.
     * @return The calculated total number of pages.
     */
    private int calculateTotalPages(final long totalMatches, final long hitsPerPage)
    {
        if (totalMatches == 0)
        {
            return 0;
        }

        final int totalPages = (int) (Math.ceil((double) totalMatches / hitsPerPage));
        return totalPages;
    }

    /**
     * Create the search query either using predicateMap.
     * 
     * @param resourceResolver The resource resolver.
     * @param predicateParamMap The parameters to use for the query.
     * @return The search query.
     */
    private Query createQuery(final ResourceResolver resourceResolver, final Map<String, String> predicateParamMap)
    {
        final QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class);
        final Session session = (Session) resourceResolver.adaptTo(Session.class);

        Query query = null;
        query = queryBuilder.createQuery(PredicateGroup.create(predicateParamMap), session);
        return query;
    }

}

上述源类的测试类:

public class SearchServiceImplTest
{

    private SearchServiceImpl searchService;
    private SearchResult result;
    private HashMap<String, String> predicateParameterMap;
    private ResourceResolver resourceResolver;
    private QueryBuilder queryBuilder;
    private Session session;
    private Query query;
    private PredicateGroup predicateGroup;
    private java.util.List<Hit> hits;
    private SlingHttpServletRequest request = null;
    private com.project.digital.models.SearchResult searchResult;
    private static long TEST_START_INDEX = 0;
    private static long TEST_HITS_PER_PAGE = 2;
    private static long TEST_TOTAL_MATCHES = 5;

    private static String TEST_SEARCH_ROOT_PATH = "/content/testSite/en";

    @SuppressWarnings("unchecked")
    @Before
    public void setUp() throws Exception
    {
        searchService= spy(new SearchServiceImpl());
        predicateParameterMap = mock(HashMap.class);
        result = mock(SearchResult.class);
        request = mock(SlingHttpServletRequest.class);
        resourceResolver = mock(ResourceResolver.class);
        queryBuilder = mock(QueryBuilder.class);
        session = mock(Session.class);
        query = mock(Query.class);
        predicateGroup = mock(PredicateGroup.class);
        hits = (java.util.List<Hit>) mock(List.class);

        searchResult = new com.project.digital.models.SearchResult();

        Mockito.when(new com.project.digital.models.SearchResult()).thenReturn(searchResult);
        when(request.getResourceResolver()).thenReturn(resourceResolver);
        when(resourceResolver.adaptTo(QueryBuilder.class)).thenReturn(queryBuilder);
        when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
        when(PredicateGroup.create(predicateParameterMap)).thenReturn(predicateGroup);
        when(queryBuilder.createQuery(predicateGroup, session)).thenReturn(query);
        when(query.getResult()).thenReturn(result);
    }


    private void mockSearchResult(long startIndex, long hitsPerPage, long totalMatches, List<Hit> hits)
    {
        when(result.getStartIndex()).thenReturn(startIndex);
        when(result.getHitsPerPage()).thenReturn(hitsPerPage);
        when(result.getTotalMatches()).thenReturn(totalMatches);
        when(result.getHits()).thenReturn(hits);

    }
}

当我在测试类中使用PredicateGroup时,我得到了这个异常。

共有1个答案

沈枫涟
2023-03-14

添加-noverify作为JVM参数。

我们遇到了同样的问题,一个来自java的VerifyError。朗朗,上课。getDeclaredConstructors0(),其Powermock ClassImposterizer类位于堆栈跟踪的更上层。

我们的依赖关系也几乎与您的相同-我们使用jUnit 4.12而不是4.11,但是PowerMock(1.6.2)和Mockito(1.10.19)的版本相同。

因为我们使用Jenkins来启动Ant脚本而不是Maven,所以我将此参数添加到junit Ant任务中-您必须根据Maven的情况进行修改

<jvmarg line="-noverify"/>

当然,我们不希望"-no验证"应用于我们所有的测试,所以我从主套件中提取了碰到VerifyError异常的测试,并单独运行它。你的背景可能不同。

 类似资料:
  • 在Maven项目中,我使用PowerMock easymock运行jUnit测试用例。但是,在进行“mvn清洁安装”时,我的输出低于。。 运行TestSuite测试运行:2,失败:0,错误:0,跳过:0,运行时间:0.621秒 结果: 测试运行:2,失败:0,错误:0,跳过:0 但我还有很多其他的测试用例。这是pom的一部分。xml 如果我删除PowerMock依赖项并执行“mvn clean i

  • 上周,我们的团队决定从Netbean迁移到Eclipse,因为我们开发了一些只能在Eclipse上运行的新插件。 首先,项目开始使用来自pom的my maven插件

  • 我正在尝试运行我的java类来读取GML文件,我使用Tinkerpop和GMLReader来实现这一点,问题是当我尝试使用spark运行它时,它会给我一个异常 我编写了一个简单的测试代码: 我用来运行类的命令: 错误:

  • 我看到了很多基于maven pom.xml构建文件的spring项目。还有一件奇怪的事情:在没有公共静态void main()方法的情况下构建项目。例如:https://github.com/geowarin/spring-mvc-security。在Spring.io的常用示例中,有一些类带有@SpringBootApplication注释和SpringApplication.Run(appli

  • 我在网上搜索并找到了以下资源,我尝试了这些资源(请参见pom),但无法工作: 1)Spark用户邮件列表:http://apache-spark-user-list.1001560.n3.nabble.com/packaging-a-spark-job-using-maven-td5615.html 2)如何打包spark scala应用程序 我有一个简单的例子来演示这个问题,一个简单的1类项目(

  • 问题内容: 这是一个基本问题,我只是不太熟悉Maven多模块结构。说,我有一个Web应用程序。我想将一些模块连接到它(某些服务)。我是否需要仅将其中一个模块(依赖于其他模块)制作为一个Web应用程序,然后运行它?一开始我以为我可以运行整个项目,但是这个选项在我的IDE中是无效的(我现在正在使用NetBeans),这使我认为我应该运行一个类似于主模块的东西(在这种情况下为Web应用程序) )。是这样