我正在尝试为预配服务编写Junit。该服务最终会调用VICE客户端并获得证书。当测试中运行Junit时,这浪费了证书,而我想模拟此外部调用。
类结构看起来像这样
class MyService {
public void provisionTenant() {
CLient client = generateCertificateClient(Some Params);
client.enrollCertificate(enrollmentRequest);
}
//Private Method 1
private generateCertificateCleint(Some Params) {
return new CertClient(createSslContext(), endpoint);
}
//Private Method 2
private createSslContext() {
//Do something and return context
return sslContext;
}
}
// Second Class which is accessed using the new construct in the Service Class
class CertClient {
private SSLContext;
CertClient(SSLContext) {
this.sslContext = ssslContext;
}
public enrollCertificate(enrollmentRequest) {
final URL enrollUrl = asURL(serviceEndpointUrl, RequestType.ENROLL.value());
executeRequest(enrollURL, enrollmentRequest, POST.value)
}
private byte[] executeRequest(final URL url, final Vice2Request request, final String httpMethod) {
//Do a bunch of steps and return certificate s bytes
HTTPConnection.writeOutPutStream();
return getCerttificateAsBVytes(HTTPConnection);
}
//Return the Certificate fetched from the Generic POST call
byte[] getCerttificateAsBytes(HTTPConnection connection) {
try (InputStream inputStream = connection.getInputStream()) {
return readBytes(inputStream, responseLength);
}
}
}
我有两个挑战,一个是我能够在两个类中的大多数代码上获得83%的覆盖率,但是如果我模拟整个客户端类,那么我将失去代码覆盖率。
有没有一种方法可以模拟第二个类(即客户端类)中的HTTPConnection post调用,客户端不是服务中的Field,但是我可以重构代码并将其设置为Field,但仍然可以通过NEW在方法调用中实例化,有没有办法模拟这个?
我尝试通过为Default CLient .class提供测试准备来尝试PowerMockito.whenNew,但该方法无效,它始终会创建一个新对象。 其次,如何模拟服务->(实例化)Cleint->(实例化)HttpConnection。我该如何模拟两个级别的变量?
@Before
public void setUp() throws NoSuchFieldException {
MockitoAnnotations.initMocks(this);
ResponseBodyString = "<ResponseBOsy>"
}
@Test
public void provisionKeyStoreTest() throws Exception {
PowerMockito.mockStatic(SystemUtil.class);
PowerMockito.when(SystemUtil.isStoreProvEnabled()).thenReturn(true);
CertClient certClient = PowerMockito.mock(CertClient.class);
PowerMockito.whenNew(CertClient.class).withAnyArguments().thenReturn(certClient);
SomeCaller.provisionTenant();
}