'Mocking new object method call in Junit5

I have mocked another class method called Which is called at production like new B().somemethod (arg) has return type void and newD().anymenthod() it has return type inputstream

In the test method, I am doing mocking Like donothing().when(b). somemethod ();

And

When(d.anymehod()).thenreturn(inputstream);(here inputstrem i am providing)

Here I already did @Mock B b;

@Mock D d;

Here my test case run successfully but mocked method was also called at that time.

Here I didn't want to alter the production code only test cases implementation can be altered.

class TestSystem {
    @InjectMock
    System sys;

    @Mock 
    B b;
    @Mock
    D d;

    @BeforeEach
    void setup() {
        MockitoAnnotation.openMocks(this);
    }

    @Test
    testModule() {
        InputStrem input = null;
        when(d.anymethod()).thenReturn(inputStrem);
        doNothing().when(b).somemethod();
        sys.module();
    }
        
Class System{
    public void module() {
        //some code .....
    
        new B().somemethod();
    
        inputStrem = new D().anymethod(value);
    }

Class B {
    public void somemethod(){
    //some code .....
    }
}


Class D {
    public InputStrem anymethod() {
        //some code ......

    }    
}


Solution 1:[1]

Try to initialise Mock like this:

  @InjectMocks
  private System sys;

  @Mock 
  B b;
  @Mock
  D d;

  private AutoCloseable closeable;

  @BeforeEach
  void init() {
    closeable = MockitoAnnotations.openMocks(this);

  }

  @AfterEach
  void closeService() throws Exception {
    closeable.close();

  }


  @Test
  testModule(){...}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siddharth Aadarsh