[英]how to write a unit test case to verify the signatures?
我對 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 function 編寫測試用例,我應該如何設置此方法的期望值?
單元測試的基本目的是檢查業務邏輯在所有可能的場景中是否按預期工作。
編寫它的目標應該是盡可能地破壞代碼。
因此,應該考慮提供所有可能的輸入並測試代碼的正確性。 - 正面案例 - 負面案例 - 異常案例 - 代碼容易中斷的邊界條件。 - Null 值、空字符串等。必須為業務邏輯中的所有可能流程編寫測試用例。 以下是您應該涵蓋的一些基礎知識-
/*
* 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);
}
除此之外,如果我們按照您的邏輯 go,則基於SnsRequest
object 的類型有 2 個不同的流程。 因此也必須為這些案例編寫測試用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.