Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock objects initialized in constructor using an external method call?

final HttpClient httpClient;

final HttpUtils httpUtils;

@Autowired
public SampleConstructor(HttpUtils httpUtils) {

    this.httpClient = ApacheHttpSingleton.getHttpClient();
    this.httpUtils = httpUtils;
}

So I have this class having two objects which I am initializing using the autowired constructor. While writing the JUnit tests for this class, I have to mock the two objects. The HttpUtils object is straightforward. However, it's the HttpClient object I am having trouble mocking.

@Mock
HttpUtils mockHttpUtils;

@Mock
HttpClient mockHttpClient;

@InjectMocks
SampleConstructor mockService;

The above approach works for HttpUtils but not for HttpClient. Can someone please help me with how I can inject the mocked object for HttpClient?

like image 205
Mayank Aggarwal Avatar asked Jun 11 '26 15:06

Mayank Aggarwal


1 Answers

Create a package-private constructor that takes both objects as its parameters. Place your unit test in the same package (but in src/test/java/) so it has access to that constructor. Send in mocks to that constructor:

final HttpClient httpClient;
final HttpUtils httpUtils;

@Autowired
public SampleConstructor(HttpUtils httpUtils) {
    this(ApacheHttpSingleton.getHttpClient(), httpUtils);
}

// For testing
SampleConstructor(HttpClient httpClient, HttpUtils httpUtils) {
    this.httpClient = httpClient;
    this.httpUtils = httpUtils;
}

Then in your test:

@Mock
HttpUtils mockHttpUtils;

@Mock
HttpClient mockHttpClient;

SampleConstructor c = new SampleConstructor(mockHttpClient, mockHttpUtils);
like image 59
nickb Avatar answered Jun 13 '26 04:06

nickb