0

I am writing down jUnit for legacy code. Scenario is as below:

Class A{
     B b = new B(1,2,3);
 }

is there any way to mock or override b with object created by me with customer params.

Christopher Schneider
  • 3,745
  • 2
  • 24
  • 38
Atul Kumar
  • 99
  • 8
  • Yes, by using reflection. There's a built-in way to do this with Mockito using `@InjectMocks`. https://stackoverflow.com/questions/16467685/difference-between-mock-and-injectmocks – Christopher Schneider Apr 08 '22 at 20:16
  • @ChristopherSchneider thanks, that worked. but what if initialisation in happening inside method. That mock value is getting override by the initialisation. – Atul Kumar Apr 08 '22 at 20:21
  • Not without changing at least some of the legacy code. Option 1: inject a factory into `A` which knows how to create instances of `B`. The test injects a mock factory which can provide a mock `B`. Option 2 (ugly): extract `b= new B(1,2,3)` to a protected method. @Spy the instance being tested, and override that protected method to provide a mock `B`. – Andrew S Apr 08 '22 at 20:30
  • Thanks @AndrewS option 1 looks better. – Atul Kumar Apr 09 '22 at 07:17

1 Answers1

0

As per the comments, one way was to use InjectMocks, but since you were asking if there is a way to mock a constructor call if it is inside a method, the answer is yes, you can use Mockito's inline mock maker, and then mock the construction.

 assertEquals("foo", Foo.method());
 try (MockedConstruction mocked = mockConstruction(Foo.class)) {
     Foo foo = new Foo();
     when(foo.method()).thenReturn("bar");
     assertEquals("bar", foo.method());
     verify(foo).method();
 }
 assertEquals("foo", foo.method());

As per the official documentation, it is turned off by default

This mock maker is turned off by default because it is based on completely different mocking mechanism that requires more feedback from the community. It can be activated explicitly by the mockito extension mechanism, just create in the classpath a file /mockito-extensions/org.mockito.plugins.MockMaker containing the value mock-maker-inline.

So I would suggest you to create that file, also you can refer to this section in the Official Mockito Documentation

Do remember to add the latest version of mockito-inline maven dependency

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-inline -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>4.3.1</version>
    <scope>test</scope>
</dependency>
Parth Manaktala
  • 1,112
  • 9
  • 27