2014-09-30 60 views
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 
+2

不要用静力学来做这件事,也不要让这个班最终成绩。当单元测试与之协作的类时,它将无法嘲笑这个对象。 – 2014-09-30 20:36:43

+0

问题不在于静态,你只需要在你的密码上调用init:http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html – Renato 2014-09-30 20:54:34

+0

@ Renato我确实有init致电。请参阅更新的问题代码 – 2014-09-30 21:00:41

回答

0

的问题是,你不能初始化对象两次。您需要一个用于解密模式的静态实例,一个用于加密模式,另一个用于您想要使用的任何其他模式。你需要将init调用从方法移动到静态构造函数(尽管我同意工程师Dollery说这不应该是静态的)。

相关问题