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.
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.
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 valuemock-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>