Initialization error when calling static method in unit test












0















I have a class with static method for encryption and decryption. I am writing test for these methods but I am getting java.lang.IllegalStateException with not initialized message.



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 Class



@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)));
}


Exception



java.lang.IllegalStateException: Cipher not initialized









share|improve this question




















  • 2





    Don't do this with statics, and don't make the class final. It'll make it impossible to mock out this object when unit-testing classes that collaborate with it.

    – Engineer Dollery
    Sep 30 '14 at 20:36











  • The problem is not the statics, you just need to call init on your cipher: docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

    – Renato
    Sep 30 '14 at 20:54











  • @ Renato I do have init call.See updated question code

    – αƞjiβ
    Sep 30 '14 at 21:00











  • @Engineer Dollery I am making static so that not initilZATION HASN'T TO BE DONE everytime.

    – αƞjiβ
    Sep 30 '14 at 21:02











  • According to the error message, you have not initialized it... maybe you forgot to do it somewhere? Why don't you call init right after you get an instance of it? BTW, You can use the singleton pattern to achieve the same result (init it only once) without having to make all your methods static.

    – Renato
    Sep 30 '14 at 21:04
















0















I have a class with static method for encryption and decryption. I am writing test for these methods but I am getting java.lang.IllegalStateException with not initialized message.



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 Class



@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)));
}


Exception



java.lang.IllegalStateException: Cipher not initialized









share|improve this question




















  • 2





    Don't do this with statics, and don't make the class final. It'll make it impossible to mock out this object when unit-testing classes that collaborate with it.

    – Engineer Dollery
    Sep 30 '14 at 20:36











  • The problem is not the statics, you just need to call init on your cipher: docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

    – Renato
    Sep 30 '14 at 20:54











  • @ Renato I do have init call.See updated question code

    – αƞjiβ
    Sep 30 '14 at 21:00











  • @Engineer Dollery I am making static so that not initilZATION HASN'T TO BE DONE everytime.

    – αƞjiβ
    Sep 30 '14 at 21:02











  • According to the error message, you have not initialized it... maybe you forgot to do it somewhere? Why don't you call init right after you get an instance of it? BTW, You can use the singleton pattern to achieve the same result (init it only once) without having to make all your methods static.

    – Renato
    Sep 30 '14 at 21:04














0












0








0








I have a class with static method for encryption and decryption. I am writing test for these methods but I am getting java.lang.IllegalStateException with not initialized message.



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 Class



@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)));
}


Exception



java.lang.IllegalStateException: Cipher not initialized









share|improve this question
















I have a class with static method for encryption and decryption. I am writing test for these methods but I am getting java.lang.IllegalStateException with not initialized message.



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 Class



@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)));
}


Exception



java.lang.IllegalStateException: Cipher not initialized






java unit-testing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 5:33









Cœur

18.6k9110150




18.6k9110150










asked Sep 30 '14 at 20:32









αƞjiβαƞjiβ

1,48453369




1,48453369








  • 2





    Don't do this with statics, and don't make the class final. It'll make it impossible to mock out this object when unit-testing classes that collaborate with it.

    – Engineer Dollery
    Sep 30 '14 at 20:36











  • The problem is not the statics, you just need to call init on your cipher: docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

    – Renato
    Sep 30 '14 at 20:54











  • @ Renato I do have init call.See updated question code

    – αƞjiβ
    Sep 30 '14 at 21:00











  • @Engineer Dollery I am making static so that not initilZATION HASN'T TO BE DONE everytime.

    – αƞjiβ
    Sep 30 '14 at 21:02











  • According to the error message, you have not initialized it... maybe you forgot to do it somewhere? Why don't you call init right after you get an instance of it? BTW, You can use the singleton pattern to achieve the same result (init it only once) without having to make all your methods static.

    – Renato
    Sep 30 '14 at 21:04














  • 2





    Don't do this with statics, and don't make the class final. It'll make it impossible to mock out this object when unit-testing classes that collaborate with it.

    – Engineer Dollery
    Sep 30 '14 at 20:36











  • The problem is not the statics, you just need to call init on your cipher: docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

    – Renato
    Sep 30 '14 at 20:54











  • @ Renato I do have init call.See updated question code

    – αƞjiβ
    Sep 30 '14 at 21:00











  • @Engineer Dollery I am making static so that not initilZATION HASN'T TO BE DONE everytime.

    – αƞjiβ
    Sep 30 '14 at 21:02











  • According to the error message, you have not initialized it... maybe you forgot to do it somewhere? Why don't you call init right after you get an instance of it? BTW, You can use the singleton pattern to achieve the same result (init it only once) without having to make all your methods static.

    – Renato
    Sep 30 '14 at 21:04








2




2





Don't do this with statics, and don't make the class final. It'll make it impossible to mock out this object when unit-testing classes that collaborate with it.

– Engineer Dollery
Sep 30 '14 at 20:36





Don't do this with statics, and don't make the class final. It'll make it impossible to mock out this object when unit-testing classes that collaborate with it.

– Engineer Dollery
Sep 30 '14 at 20:36













The problem is not the statics, you just need to call init on your cipher: docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

– Renato
Sep 30 '14 at 20:54





The problem is not the statics, you just need to call init on your cipher: docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

– Renato
Sep 30 '14 at 20:54













@ Renato I do have init call.See updated question code

– αƞjiβ
Sep 30 '14 at 21:00





@ Renato I do have init call.See updated question code

– αƞjiβ
Sep 30 '14 at 21:00













@Engineer Dollery I am making static so that not initilZATION HASN'T TO BE DONE everytime.

– αƞjiβ
Sep 30 '14 at 21:02





@Engineer Dollery I am making static so that not initilZATION HASN'T TO BE DONE everytime.

– αƞjiβ
Sep 30 '14 at 21:02













According to the error message, you have not initialized it... maybe you forgot to do it somewhere? Why don't you call init right after you get an instance of it? BTW, You can use the singleton pattern to achieve the same result (init it only once) without having to make all your methods static.

– Renato
Sep 30 '14 at 21:04





According to the error message, you have not initialized it... maybe you forgot to do it somewhere? Why don't you call init right after you get an instance of it? BTW, You can use the singleton pattern to achieve the same result (init it only once) without having to make all your methods static.

– Renato
Sep 30 '14 at 21:04












1 Answer
1






active

oldest

votes


















0














The issue is that you can't initialize the object twice. You would need one static instance for decrypt mode, one for encrypt mode, and one for any other mode you want to use. You would need to move the init call from the method to the static constructor(although I agree with Engineer Dollery that this shouldn't be a static).






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26129563%2finitialization-error-when-calling-static-method-in-unit-test%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The issue is that you can't initialize the object twice. You would need one static instance for decrypt mode, one for encrypt mode, and one for any other mode you want to use. You would need to move the init call from the method to the static constructor(although I agree with Engineer Dollery that this shouldn't be a static).






    share|improve this answer




























      0














      The issue is that you can't initialize the object twice. You would need one static instance for decrypt mode, one for encrypt mode, and one for any other mode you want to use. You would need to move the init call from the method to the static constructor(although I agree with Engineer Dollery that this shouldn't be a static).






      share|improve this answer


























        0












        0








        0







        The issue is that you can't initialize the object twice. You would need one static instance for decrypt mode, one for encrypt mode, and one for any other mode you want to use. You would need to move the init call from the method to the static constructor(although I agree with Engineer Dollery that this shouldn't be a static).






        share|improve this answer













        The issue is that you can't initialize the object twice. You would need one static instance for decrypt mode, one for encrypt mode, and one for any other mode you want to use. You would need to move the init call from the method to the static constructor(although I agree with Engineer Dollery that this shouldn't be a static).







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Sep 30 '14 at 21:35









        SignSign

        1,5691527




        1,5691527
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26129563%2finitialization-error-when-calling-static-method-in-unit-test%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to change which sound is reproduced for terminal bell?

            Can I use Tabulator js library in my java Spring + Thymeleaf project?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents