10

I am trying to write a test case for the method decrypt here.

    private static Codec codec;

    static {
        try {
            codec = new Codec(encryptionType, encryptionKey, false, true, false);
        } catch (CodecException e) {
            throw new RuntimeException("Codec initialisation failed", e);
        }
    }


    public static String decrypt(final String toDecrypt) throws CodecException {
        String decrypted = codec.decryptFromBase64(toDecrypt);
        if (decrypted.endsWith(":")) {
            decrypted = decrypted.substring(0, decrypted.length() - 1);
        }
        return decrypted;
    }

Test Case:

    @Mock
    private Codec codec;
    @Test
    public void test_decrypt_Success() throws CodecException {
        when(codec.decryptFromBase64(TestConstants.toDecrypt)).thenReturn(TestConstants.decrypted);
        assertEquals(DocumentUtils.decrypt(TestConstants.toDecrypt), TestConstants.decrypted);
    }

Since this is a static method, I can't inject an instance of the class in the test suite and mock its codec. The above code throws an error from the codec library at assert as expected.

What is your approach to testing static methods like this? Or should I not be writing tests for this at all?

4
  • Possible duplicate of Mock/Stub super constructor invocation in Java for unit testing Commented Dec 10, 2018 at 10:39
  • Use PowerMock to mock static methods. But you are not even calling the decrypt(final String toDecrypt) method in your Junit. Without that, the statement when(codec.decryptFromBase64(TestConstants.toDecrypt)).thenReturn(TestConstants.decrypted); has no meaning. Commented Dec 10, 2018 at 10:43
  • @AnkurChrungoo my bad. Updated the q. I meant to call decrpyt in assert. Commented Dec 10, 2018 at 10:46
  • @talex, I am not trying to mock a constructor or a super constructor. I want to mock a static variable initialised in static block in a static method. Commented Dec 10, 2018 at 10:48

3 Answers 3

5

In Java, static methods are not designed to set dependencies.
So switching the dependency into a mock is really not natural.
You could provide a static setter for the field such as :

private static Codec codec;
public static void setCodec(Codec codec){
   this.codec = codec;
}

And you could set a mock with setCodec(...) but ugh...

But forget, just do things well : refactor the code to remove all static and introduce a constructor that sets the codec.

private Codec codec;
public MyClassUnderTest(Codec codec){
   this.codec codec;
}

IOC could help here to make the class under test a singleton and ease the dependency injections.
If not possible in your case, Java 5 enumeration could help you for at least the singleton concern.

Sign up to request clarification or add additional context in comments.

14 Comments

I was not using the static eariler. But a peer pointed out that this is a util class and as such I should be initialising the codec only once. How do we write mocks for util static classes?
@tanvi I suspected the same! You have some choices like writing proper object oriented code and move this code into a separate class which does this specific job and non-statically...... or write the static setter and adapt the code accordingly...or use PowerMockito to mock static methods:) Refer blog.codecentric.de/en/2011/11/… for PowerMockito example.
I agree with a single initialization but I don't about static usage. Ok in Java static methods are easy to write and simplify client usage for util methods. But it also hs some limitations : this hardcodes dependencies and so make it no naturally switchable. I generally write static methods only for methods that never need to mock any things. About your question, the setter is a way. PowerMock is another one. But I would avoid both in your case as you are the api/component developer.
@davidxxx, yes, I would rather suggest separating this code out into a singleton class since it has a codec dependency. This shall make it easier to test it/mock it.
If you don't want to change your mind, stay on my initial comment : powermock or the static setter.
|
2

There are many different and shortcut ways of achieving the same (as pointed out in comments and other answers), but not all of them are good in the long run especially.

I would suggest creating a Singleton class which implements the Decrypt functionality. So, you won't have to create multiple instances, and don't really need to have static method for decrypting as well, and you can inject your codec once and more easily (I assume you don't have multiple types of codec as per your comments. But, if you do, then the functionality shall be adapted accordingly).

For more reference: Why use a singleton instead of static methods?

For reference on why static should be used carefully:- Why are static variables considered evil?

2 Comments

Agree concerning the main idea but in Java I prefer IOC to old singleton way with the static getInstance() method.
@davidxxx, yes, but many times that doesn't suit us, although that is the most ideal way in the long run.
1

In my experience in those cases I just prepare all instances in a @Before method:

private Codec codec;

@Before
public void setup() throws CodecException {
  codec = new Codec(encryptionType, encryptionKey, false, true, false);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.