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

标签 java junit mockito powermock powermockito

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/

相关文章:

java - JUnit : Is there a way to skip a test belonging to a Test class's parent?

java - 在 junit 4.11-SNAPSHOT 中使用@Parameters 注解

java - 在 LINUX 操作系统中从 JAVA 应用程序创建用户

java - Android:指定数组大小?

java - Gson序列化问题与反斜杠java

java - 在单元测试中验证私有(private)方法调用的顺序

java - 需要启动Tomcat服务器来测试Junit测试用例

java - 什么是NullPointerException,我该如何解决?

junit - 如何仅对单元测试禁用 Jersey 过滤器(使用spring-boot)

java - 在对类方法进行单元测试时模拟子类的方法