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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With