0

Here is what I want to achieve.

public class A {
    protected final Config config;
    protected final Connection connection;

    public A(Config config) {
        this.config = config;
        this.connection = new Connection("a", "b");
    }
    
    public void someMethod() {
    }
}

When I try to test some underlying methods for the class A, I would want to mock the connection object creation. How can I do that, I have tried all possible ways but didn't find any luck.

Pankaj Rathi
  • 65
  • 1
  • 11
  • Use the Mock method, or Mock annotation. Then, stub the method to return whatever value you expect the connection to return [Read also](https://www.baeldung.com/java-spring-mockito-mock-mockbean) – experiment unit 1998X Jan 11 '23 at 09:57
  • I have done that, I mocked the Connection class but how do I stub the constructor because I'm calling the constructor – Pankaj Rathi Jan 11 '23 at 10:01
  • The obvious solution and best practice is to refactor to not instantiate an object within class A's constructor. If Connection has side effects it should be provided via dependency injection. Now to answer your question if you still insist on doing it this way then here's an exactly the same question with some answers. https://stackoverflow.com/questions/11214136/unit-testing-with-mockito-for-constructors Also you could just create a setter for the connection field and make it non final, inject a mock that way. – Igor Flakiewicz Jan 11 '23 at 10:14
  • Thanks @IgorFlakiewicz, I think I will go with refactoring where I pass the connection object as part of A's constructor and that way it will be more easy for me to mock and also refactoring can be easy. – Pankaj Rathi Jan 11 '23 at 10:38

0 Answers0