我对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 函数编写测试用例,我应该如何设置对此方法的期望?
最佳答案
单元测试的基本目的是检查业务逻辑在所有可能的场景中是否按预期工作。
编写代码时的目标应该是尽可能地破坏代码。
因此,应该考虑提供所有可能的输入并测试代码的正确性。 - 阳性病例 - 负面案例 - 异常(exception)情况 - 代码容易崩溃的边界条件。 - 空值、空字符串等。 必须为业务逻辑中所有可能的流程编写测试用例。 以下是您应该涵盖的一些基础知识 -
/*
* 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 个不同的流程。因此也必须为这些情况编写测试用例。
关于java - 如何编写单元测试用例来验证签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58471134/