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