6

I want to mock my java class in such a ways so that each and every new instance of it should return the mocked response.

  • you could name the class AlwaysMocked – wero Sep 22 '15 at 16:41
  • May be you should create a factory class with a getInstance() method and return a mock object from this method. Instead of calling new, call the getInstance() that will always return a mock object. – user2953113 Sep 22 '15 at 16:51

2 Answers2

2

There are two mocking libraries which support this: PowerMock (as shown in Matthias' answer), and JMockit.

In the second case, the test only needs to declare a mock field or mock parameter using the @Mocked annotation.

Rogério
  • 16,171
  • 2
  • 50
  • 63
  • I am not familiar with `JMockit`, but I would expect that using `@Mocked` on an delared mock field, will create one mocked instance that's assigned to the field. It would be surprised, if it would "intercept" a call `new MyOriginalClass()` to create a mocked object instead. – Matthias J. Sax Jun 08 '19 at 02:55
  • 1
    @MatthiasJ.Sax Once a class is `@Mocked`, all of its instances are mocked; simple as that. The instance that gets created and assigned to the mock field (or test method parameter) is a *representative* of all such instances, for the purposes of recording and/or verifying expectations. So, a `new MyOriginalClass()` constructor execution does get "intercepted", but that *is* the mocked instance itself, no need to create another. – Rogério Jun 08 '19 at 16:51
  • Interesting. Thanks for clarifying! – Matthias J. Sax Jun 09 '19 at 01:20
1

It's basically:

PowerMockito.whenNew(MyOriginalClass.class).withNoArguments().thenReturn(new MyMockClass());

You also need to use @RunWith(PowerMockRunner.class) and @PrepareForTest(ClassThatCallsConstructorOfMyOriginalClass.class) as class annotation of you JUnit test class. If you have multiple classes that instantiate MyOriinalClass you can also specify whole packages: @PrepareForTest("com.mypackage.*")

Matthias J. Sax
  • 59,682
  • 7
  • 117
  • 137