首页 > 解决方案 > 如何编写单元测试用例来验证签名?

问题描述

我对 mockito 很陌生,我想为我们使用证书验证签名的场景编写一个单元测试,我的代码是这样的,

***public boolean messageSignatureValidation(SNSRequest snsRequest) {
        try {
            URL url = new URL(snsRequest.getSigningCertURL());
            InputStream inStream = url.openStream();
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
            inStream.close();
            Signature sig = Signature.getInstance("SHA1withRSA");
            sig.initVerify(cert.getPublicKey());
            sig.update(getMessageBytesToSign(snsRequest));
            return sig.verify(Base64.decodeBase64(snsRequest.getSignature()));
        }
        catch (Exception e) {
            throw new SIOInternalServerException(SIOErrors.SIO109500.toString(), "Signature verification failed");
        }
    }
    private static byte [] getMessageBytesToSign (SNSRequest snsRequest) {
        byte [] bytesToSign = null;
        if (snsRequest.getType().equals(NOTIFICATION_MESSAGE))
            bytesToSign = snsRequest.toString().getBytes();
        else if (snsRequest.getType().equals(SUBSCRIPTION_CONFIRMATION) || snsRequest.getType().equals(UNSUBSCRIBE_MESSAGE))
            bytesToSign = snsRequest.toString().getBytes();
        return bytesToSign;
    }***

我正在尝试为 messageSignatureValidation 函数编写测试用例,我应该如何设置此方法的期望?

标签: javamockito

解决方案


单元测试的基本目的是检查业务逻辑在所有可能的场景中是否按预期工作。

编写它的目标应该是尽可能地破坏代码。

因此,应该考虑提供所有可能的输入并测试代码的正确性。- 正面案例 - 负面案例 - 异常案例 - 代码容易中断的边界条件。- 空值、空字符串等。必须为业务逻辑中的所有可能流程编写测试用例。以下是您应该涵盖的一些基础知识-

    /*
 * testCase That checks happy scenario 
 */
@Test
public void testMessageSignatureValidationSuccess() throws Exception {

    SNSRequest snsRequest = new SNSRequest();
    snsRequest.setSignature("sampleTestinput");
    snsRequest.setType("type");
    snsRequest.setSigningCertURL("https://localhost:7077");
    boolean verify =messageSignatureValidation(snsRequest);
    assertTrue( verify);

}

/*
 * testCase That checks when validation fails 
 */
@Test
public void testMessageSignatureValidationFailed() throws Exception {

    SNSRequest snsRequest = new SNSRequest();
    snsRequest.setSignature("sampleTestinput");
    snsRequest.setType("type");
    snsRequest.setSigningCertURL("https://localhost:7077");
    boolean verify =messageSignatureValidation(snsRequest);
    assertFalse( verify);

}

/*
 * testCase That checks when validation throws error 
 */
@Test(expected = Exception.class)
public void testMessageSignatureValidationthrowsException() throws Exception {

    SNSRequest snsRequest = new SNSRequest();
    snsRequest.setSignature("sampleTestinput");
    snsRequest.setType("type");
    snsRequest.setSigningCertURL("https://localhost:7077");
    messageSignatureValidation(snsRequest);

} 

除此之外,如果我们按照您的逻辑,根据SnsRequest对象的类型有 2 种不同的流程。因此也必须为这些案例编写测试用例。


推荐阅读