我对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函数编写测试用例,我应该如何为该方法设置期望值?
答案 0 :(得分:0)
单元测试的基本目的是检查业务逻辑在所有可能的情况下是否按预期工作。
编写代码的目的应该是尽可能地破坏代码。
因此,应该考虑提供所有可能的输入并测试代码的正确性。 -积极案例 -负面案件 -例外情况 -代码容易中断的边界条件。 -空值,空字符串等 必须为业务逻辑中的所有可能流编写测试用例。 这里是您应了解的一些基本知识-
/*
* 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种不同的流程。因此,也必须为这些情况编写测试用例。