gpt4 book ai didi

java - 如何使用mockito/powermockito模拟IamRequest impl类?

转载 作者:行者123 更新时间:2023-11-30 06:59:14 25 4
gpt4 key购买 nike

IamRequestImpl.java

public class IamRequestImpl<E> extends IamRequest {
public IamRequestImpl(Iam iam, String s, String s1, Object o, Class aClass) {
super(iam, s, s1, o, aClass);
}
}

GcsHelper.java

public <T> T getServiceAccountKey(IamRequestInitializer req, Iam iam, String requestString,
String api) throws IOException {
IamRequestImpl<String> iamRequestImpl= new IamRequestImpl<String>(iam, HttpMethods.POST, requestString, String.class,
ServiceAccountKey.class);
iamRequestImpl.setKey(api);
iamRequestImpl.setFields(SchedulerConstants.JSON_KEY_FIELDS);
req.initializeJsonRequest(iamRequestImpl);
return (T) request.execute();
}

GCSHelperTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({ IamRequestImpl.class, ServiceAccountKey.class})
@Test
public void testGetServiceAccountKeyOnSuccess() throws Exception{
IamRequestInitializer mockIamRequestInitializer = Mockito.mock(IamRequestInitializer.class);
IamRequestImpl<String> mockIamRequestImpl = PowerMockito.mock(IamRequestImpl.class);
PowerMockito.whenNew(IamRequestImpl.class).withAnyArguments().thenReturn(mockIamRequestImpl);
when(mockIamRequestImpl.setKey("apiKey")).thenReturn(mockIamRequestImpl);
when(mockIamRequestImpl.setFields("apiKey")).thenReturn(mockIamRequestImpl);
Mockito.doNothing().when(mockIamRequestInitializer).initializeJsonRequest(mockIamRequestImpl);
spyGCSUtils.getServiceAccountKey(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
}

运行 testGetServiceAccountKeyOnSuccess 测试用例时,面临 nullpointerException,因为 iamRequestImpl 不是模拟。

最佳答案

尝试将 Mockito.any() 转换为特定的对象,如下所示。

spyGCSUtils.getServiceAccountKey((IamRequestInitializer)Mockito.any(), (Iam)Mockito.any(), Mockito.anyString(), Mockito.anyString());

getServiceAccountKey(IamRequestInitializer, Iam, String, String)

关于java - 如何使用mockito/powermockito模拟IamRequest impl类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com