2014-09-30 144 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說這不應該是靜態的)。

相關問題