aliyun-openapi-java-sdk icon indicating copy to clipboard operation
aliyun-openapi-java-sdk copied to clipboard

How to write Unit Test for these APIs like KMS

Open River-java opened this issue 4 years ago • 1 comments

  • 产品和接口:
  • KMS
  • DecryptRequest
  • 平台:
  • 最小代码: KMS APS like below:
IClientProfile profile = DefaultProfile.getProfile(xxx, xxx, xxx);
DefaultAcsClient client = new DefaultAcsClient(profile)
DecryptRequest request = new DecryptRequest();
DecryptResponse response = client.getAcsResponse(request);

How can I write UT and no need to access Aliyun service?

River-java avatar Jul 21 '21 06:07 River-java

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class MyKMSClassTest {

    @Mock
    DefaultAcsClient mockClient;

    @Mock
    DecryptResponse mockResponse;

    @InjectMocks
    MyKMSClass myKMSInstance;

    @Test
    public void testDecryptValue() throws Exception {
        when(mockClient.getAcsResponse(any(DecryptRequest.class))).thenReturn(mockResponse);
        when(mockResponse.getDecryptedValue()).thenReturn("DecryptedValue");

        String decryptedValue = myKMSInstance.decryptValue();

        assertEquals("DecryptedValue", decryptedValue);
        verify(mockClient, times(1)).getAcsResponse(any(DecryptRequest.class));
        verify(mockResponse, times(1)).getDecryptedValue();
    }
}

ljluestc avatar Sep 03 '23 03:09 ljluestc