java - 如何编写单元测试用例来验证签名?
问题描述
我对 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 函数编写测试用例,我应该如何设置此方法的期望?
解决方案
单元测试的基本目的是检查业务逻辑在所有可能的场景中是否按预期工作。
编写它的目标应该是尽可能地破坏代码。
因此,应该考虑提供所有可能的输入并测试代码的正确性。- 正面案例 - 负面案例 - 异常案例 - 代码容易中断的边界条件。- 空值、空字符串等。必须为业务逻辑中的所有可能流程编写测试用例。以下是您应该涵盖的一些基础知识-
/*
* 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 种不同的流程。因此也必须为这些案例编写测试用例。
推荐阅读
- flutter - 有什么办法可以让我在颤振中构建一个 android 应用程序/内容拦截器
- python - 使用 Python 和元素树查找和替换标签内的 XML 数据
- java - 使用 JNA 发布到 POSIX 信号量
- python - 在 xml 中创建具有命名空间的子元素
- oracle - 如何在plsql中以动态方式从多个表中导出数据
- javascript - 如何捕获 @Html.DisplayFor 数据并将其传递给 javascript/jQuery 代码部分?
- r - 在数据框中划分两列并将结果放在现有列中,但通过索引而不是名称引用列
- winapi - 如何测试可等待计时器是否已激活?
- javascript - 如何在 reduce 方法中使用 switch 语句?
- java - 为什么在基于注释的 Spring 应用程序中,@Value 默认值被解析为 null?