如何使用外部方法调用模拟在构造函数中初始化的对象?

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;
}

所以我有这个 class 有两个对象,我正在使用自动装配的构造函数对其进行初始化。在为此 class 编写 JUnit 测试时,我必须模拟这两个对象。 HttpUtils 对象很简单。但是,这是我在模拟时遇到问题的 HttpClient 对象。

@Mock
HttpUtils mockHttpUtils;

@Mock
HttpClient mockHttpClient;

@InjectMocks
SampleConstructor mockService;

上述方法适用于 HttpUtils 但不适用于 HttpClient。有人可以帮助我如何为 HttpClient 注入模拟对象吗?

创建一个将两个对象作为参数的包私有构造函数。将您的单元测试放在同一个包中(但在 src/test/java/ 中),以便它可以访问该构造函数。将模拟发送到该构造函数:

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;
}

那么在你的测试中:

@Mock
HttpUtils mockHttpUtils;

@Mock
HttpClient mockHttpClient;

SampleConstructor c = new SampleConstructor(mockHttpClient, mockHttpUtils);