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 8732285
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T09:24:45+00:00 2026-06-13T09:24:45+00:00

I want to mock a Class in Mockito. It will then have a .newInstance()

  • 0

I want to mock a Class in Mockito. It will then have a .newInstance() call issued which will be expected to return an actual class instance (and will return a mock in my case).

If it was setup correctly then I could do:

ArrayList myListMock = mock(ArrayList.class);
when(myVar.newInstance()).thenReturn(myListMock);

I know I can set it up so that a new instance of class ArrayList will be a mock (using PowerMockito whenNew), just wondering if there was a way to mock this kind of a class object so I don’t have to override instance creation…

Below is the real class I’m trying to mock, I can’t change the structure it is defined by the interface. What I’m looking for is a way to provide cvs when initialize is called.

public class InputConstraintValidator 
    implements ConstraintValidator<InputValidation, StringWrapper> {

    Class<? extends SafeString> cvs;

    public void initialize(InputValidation constraintAnnotation) {
        cvs = constraintAnnotation.inputValidator();
    }

    public boolean isValid(StringWrapper value, 
                   ConstraintValidatorContext context) {

        SafeString instance;
        try {
             instance = cvs.newInstance();
        } catch (InstantiationException e) {
            return false;
        } catch (IllegalAccessException e) {
            return false;
    }
}
  • 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-13T09:24:46+00:00Added an answer on June 13, 2026 at 9:24 am

    Mockito is designed exclusively for mocking instances of objects. Under the hood, the mock method actually creates a proxy that receives calls to all non-final methods, and logs and stubs those calls as needed. There’s no good way to use Mockito to replace a function on the Class object itself. This leaves you with a few options:

    1. I don’t have experience with PowerMock but it seems it’s designed for mocking static methods.

    2. In dependency-injection style, make your static factory method into a factory instance. Since it looks like you’re not actually working with ArrayList, let’s say your class is FooBar instead:

      class FooBar {
        static class Factory {
          static FooBar instance;
          FooBar getInstance() {
            if (instance == null) {
              instance = new FooBar();
            }
            return instance;
          }
        }
        // ...
      }
      

      Now your class user can receive a new FooBar.Factory() parameter, which creates your real FooBar in singleton style (hopefully better and more threadsafe than my simple implementation), and you can use pure Mockito to mock the Factory. If this looks like it’s a lot of boilerplate, it’s because it is, but if you are thinking of switching to a DI solution like Guice you can cut down a lot of it.

    3. Consider making a field or method package-private or protected and documenting that it’s visible for testing purposes. Then you can insert a mocked instance in test code only.

      public class InputConstraintValidator implements 
          ConstraintValidator<InputValidation, StringWrapper> {
        Class<? extends SafeString> cvs;
      
        public void initialize(InputValidation constraintAnnotation) {
          cvs = constraintAnnotation.inputValidator();
        }
      
        public boolean isValid(StringWrapper value,
            ConstraintValidatorContext context) {
          SafeString instance;
          try {
            instance = getCvsInstance();
          } catch (InstantiationException e) {
            return false;
          } catch (IllegalAccessException e) {
            return false;
          }
        }
      
        @VisibleForTesting protected getCvsInstance()
            throws InstantiationException, IllegalAccessException {
          return cvs.newInstance();
        }
      }
      
      public class InputConstaintValidatorTest {
        @Test public void testWithMockCvs() {
          final SafeString cvs = mock(SafeString.class);
          InputConstraintValidator validator = new InputConstraintValidator() {
            @Override protected getCvsInstance() {
              return cvs;
            }
          }
          // test
        }
      }
      
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class which has a internal method and i want to mock
I want to mock a particular method of a class, problem i am facing
I want to mock only the GetValue method of the following class, using Moq:
want to have a Hyperlink-Button in a gridView in which I can display a
I want to test some methods that call others in the same class. They
I'm writing a JUnit test and also using Mockito, and I want to call
I have 2 classes. class SomeClass { public: int SomeFunction() { return 5; }
I have two beans of the same name and same class. I want to
Let's say I have an mock object, and I don't want to stub any
My test suite calls accepted in Object A. That function will then call insert

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.