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

pod7payv  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(334)
final HttpClient httpClient;

final HttpUtils httpUtils;

@Autowired
public SampleConstructor(HttpUtils httpUtils) {

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

所以这个类有两个对象,我正在用autowired构造函数初始化它们。在为这个类编写junit测试时,我必须模拟这两个对象。httputils对象很简单。但是,我很难模仿的是httpclient对象。

@Mock
HttpUtils mockHttpUtils;

@Mock
HttpClient mockHttpClient;

@InjectMocks
SampleConstructor mockService;

上述方法适用于httputils,但不适用于httpclient。有人能帮助我如何为httpclient注入模拟对象吗?

wkyowqbh

wkyowqbh1#

创建一个包私有构造函数,将这两个对象都作为其参数。将单元测试放在同一个包中(但是放在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);

相关问题