Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8767713
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T16:53:14+00:00 2026-06-13T16:53:14+00:00

Am trying to run this baseline unit test from Powermock. Running the code As-Is

  • 0

Am trying to run this baseline unit test from Powermock. Running the code As-Is off of that link, with both Mockito and Junit and it runs without error. Unfortunately, I need Mockito and TestNG and that gives me errors on 6 out of the 10 tests:

Mockito cannot mock this class: class replica.java.util.UUID$$PowerMock5
Mockito can only mock visible & non-final classes.

Sorry this is a long code post, but I wanted to be complete. The first test passes, the second, 5th, 6th, 7th, 9th and 10th all fail. Can this be made to work under TestNG?

EDIT – add version numbers

These results occur with Mockito V1.9.0, Powermock V1.4.12, and TestNG v6.8 (all running under Java 1.7)

Here is the code with my minor modifications:

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.doNothing;
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.verifyStatic;
import static org.powermock.api.mockito.PowerMockito.when;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.Assert;
import org.testng.IObjectFactory;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;

/**
 * Demonstrates PowerMockito's ability to mock non-final and final system
 * classes. To mock a system class you need to prepare the calling class for
 * testing. I.e. let's say you're testing class A which interacts with
 * URLEncoder then you would do:
 * 
 * <pre>
 * 
 * &#064;PrepareForTest({A.class})
 * 
 * </pre>
 */
// @RunWith(PowerMockRunner.class)
@PrepareForTest({ SystemClassUser.class })
public class SystemClassUserTest {

    @ObjectFactory
    public IObjectFactory getObjectFactory() {
        return new PowerMockObjectFactory();
    }

    @Test
    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {
        mockStatic(URLEncoder.class);

        when(URLEncoder.encode("string", "enc")).thenReturn("something");

        Assert.assertEquals("something", new SystemClassUser().performEncode());

    }

    @Test
    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {
        mockStatic(Runtime.class);

        Runtime runtimeMock = mock(Runtime.class);
        Process processMock = mock(Process.class);

        when(Runtime.getRuntime()).thenReturn(runtimeMock);
        when(runtimeMock.exec("command")).thenReturn(processMock);

        Assert.assertSame(processMock, new SystemClassUser().executeCommand());
    }

    @Test
    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {
        mockStatic(System.class);

        when(System.getProperty("property")).thenReturn("my property");

        Assert.assertEquals("my property", new SystemClassUser().getSystemProperty());
    }

    @Test
    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {
        spy(System.class);

        when(System.nanoTime()).thenReturn(2L);

        new SystemClassUser().doMoreComplicatedStuff();

        Assert.assertEquals("2", System.getProperty("nanoTime"));
    }

    @Test
    public void assertThatMockingOfCollectionsWork() throws Exception {
        List<?> list = new LinkedList<Object>();
        mockStatic(Collections.class);

        Collections.shuffle(list);

        new SystemClassUser().shuffleCollection(list);

        verifyStatic(times(2));
        Collections.shuffle(list);
    }

    @Test
    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {
        spy(System.class);

        when(System.getProperty("property")).thenReturn("my property");

        final SystemClassUser systemClassUser = new SystemClassUser();
        systemClassUser.copyProperty("to", "property");
    }

    @Test
    public void assertThatMockingStringWorks() throws Exception {
        mockStatic(String.class);
        final String string = "string";
        final String args = "args";
        final String returnValue = "returnValue";

        when(String.format(string, args)).thenReturn(returnValue);

        final SystemClassUser systemClassUser = new SystemClassUser();
        Assert.assertEquals(systemClassUser.format(string, args), returnValue);
    }

    @Test
    public void mockingStaticVoidMethodWorks() throws Exception {
        mockStatic(Thread.class);
        doNothing().when(Thread.class);
        Thread.sleep(anyLong());

        long startTime = System.currentTimeMillis();
        final SystemClassUser systemClassUser = new SystemClassUser();
        systemClassUser.threadSleep();
        long endTime = System.currentTimeMillis();
        Assert.assertTrue(endTime - startTime < 5000);
    }

    @Test
    public void mockingURLWorks() throws Exception {
        URL url = mock(URL.class);
        URLConnection urlConnectionMock = mock(URLConnection.class);

        when(url.openConnection()).thenReturn(urlConnectionMock);

        URLConnection openConnection = url.openConnection();

        Assert.assertSame(openConnection, urlConnectionMock);
    }

    @Test
    public void mockingUUIDWorks() throws Exception {
        // given
        final UUID mock = mock(UUID.class);
        mockStatic(UUID.class);
        given(UUID.randomUUID()).willReturn(mock);

        // when
        String actual = new SystemClassUser().generatePerishableToken();

        // then
        Assert.assertEquals("00000000000000000000000000000000", actual);
    }
}

If it helps out, here is a stripped down version that executes one of the failing tests:
[I wasn’t sure if I should have edited the question, I’m sorry if that is what I should have done, but where it was already too long, this approach seemed to make a bit more sense.]

import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.Assert;
import org.testng.IObjectFactory;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;

@PrepareForTest({ SystemClassUser.class })
public class SystemClassUserTest {

@ObjectFactory
public IObjectFactory getObjectFactory() {
    return new PowerMockObjectFactory();
}

@Test
public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {
    mockStatic(System.class);

    when(System.getProperty("property")).thenReturn("my property");

    Assert.assertEquals("my property", new SystemClassUser().getSystemProperty());
}
}

Now here is the SystemClassUser class similarly stripped down:

import java.io.IOException;

public class SystemClassUser {

    public String getSystemProperty() throws IOException {
        return System.getProperty("property");
    }

}

Running results in this Exception:

FAILED: assertThatMockingOfFinalSystemClassesWorks
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class replica.java.lang.System$$PowerMock0
Mockito can only mock visible & non-final classes.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T16:53:15+00:00Added an answer on June 13, 2026 at 4:53 pm

    I simply modified test case to

    public class SystemClassUserTest extends PowerMockTestCase {
        ...
    }
    

    and it works fine


    edit (one year later): I recently found System Rules library, I didn’t try it with getProperty(), but System.exit() worked exactly as I expected…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to run this script that basically reads/interprets text in from a textfile
I am trying to run this code: ItemTaxonomy iTaxonomy = from itemTaxonomy in connection.ItemTaxonomy
I'm trying to run this piece of code: strSQL = SELECT * FROM ORDER_DATA
I am trying to run this test, but I am running int a problem.
I'm trying to run this code but this error appear: Uncaught TypeError: string is
I'm trying to run this code: let coins = [50, 25, 10, 5, 2,1]
When trying to run this method I get an error: List that this enumerator
I'm trying to run this code but I get this error anytime I use
I am trying to run this code, but a is always null . I
I'm trying to run this jQuery selector: $(#label option[value=\newLabel\]) On the following code: <select

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.