0
我有一個用靜態方法進行加密和解密的類。我正在爲這些方法編寫測試,但我得到了未初始化消息的java.lang.IllegalStateException。在單元測試中調用靜態方法時出現初始化錯誤
public final class CipherUtil {
private static Logger log = Logger.getLogger(CipherUtil.class);
private static final String SECRET_KEY = "XXX";
private static Cipher cipher;
private static SecretKeySpec secretKeySpec;
static{
try {
cipher = Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
log.error(ex);
}
byte[] key = null;
try {
key = Hex.decodeHex(SECRET_KEY.toCharArray());
} catch (DecoderException ex) {
log.error(ex);
}
secretKeySpec = new SecretKeySpec(key, "AES");
}
private CipherUtil() { }
public static String encrypt(String plainText) {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
...
}
public static String decrypt(String encryptedText) {
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
...
}
}
測試類
@Test
public void testEncryptDecrypt() {
String plainText = "Secret Message";
String encryptedText = CipherUtil.encrypt(plainText);
assertThat(encryptedText, not(equalTo(plainText)));
String decryptedText = CipherUtil.decrypt(encryptedText);
assertThat(decryptedText, is(equalTo(plainText)));
assertThat(encryptedText, not(equalTo(decryptedText)));
}
異常
java.lang.IllegalStateException: Cipher not initialized
不要用靜力學來做這件事,也不要讓這個班最終成績。當單元測試與之協作的類時,它將無法嘲笑這個對象。 – 2014-09-30 20:36:43
問題不在於靜態,你只需要在你的密碼上調用init:http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html – Renato 2014-09-30 20:54:34
@ Renato我確實有init致電。請參閱更新的問題代碼 – 2014-09-30 21:00:41