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

May*_*wal 3 java junit spring mockito spring-boot

final HttpClient httpClient;

final HttpUtils httpUtils;

@Autowired
public SampleConstructor(HttpUtils httpUtils) {

    this.httpClient = ApacheHttpSingleton.getHttpClient();
    this.httpUtils = httpUtils;
}
Run Code Online (Sandbox Code Playgroud)

所以我让这个类有两个对象,我使用自动装配构造函数初始化它们。在为此类编写 JUnit 测试时,我必须模拟这两个对象。HttpUtils 对象很简单。但是,我在模拟 HttpClient 对象时遇到了麻烦。

@Mock
HttpUtils mockHttpUtils;

@Mock
HttpClient mockHttpClient;

@InjectMocks
SampleConstructor mockService;
Run Code Online (Sandbox Code Playgroud)

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

nic*_*ckb 6

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

然后在你的测试中:

@Mock
HttpUtils mockHttpUtils;

@Mock
HttpClient mockHttpClient;

SampleConstructor c = new SampleConstructor(mockHttpClient, mockHttpUtils);
Run Code Online (Sandbox Code Playgroud)

  • 这有效。谢谢。:) 之前没有想到这种方式。 (2认同)