2

In order to do the test, I mock a Cipher object, but when I run the test, its fails because it's run the cipher code instead of the mock.

So, I write a very simple test and when I run it, fails always.

My test code is:

import javax.crypto.Cipher;

import org.junit.Test;
import org.mockito.Mockito;

public class SimpleTest {
    @Test
    public void simpleTest() throws Exception {
        Cipher cipher = Mockito.mock(Cipher.class);
        cipher.doFinal(null);
        assertTrue(true);
    }
}

And the exception who produces:

java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.checkCipherState(Cipher.java:1750)
    at javax.crypto.Cipher.doFinal(Cipher.java:2157)
    at SimpleTest.simpleTest(SimpleTest.java:12)
    ...

Why is doFinal executed?

1 Answers1

1

I'm stupid.

Thanks to @JBnizet and @ShmulikKlein, thery are right.

The doFinal method, as the name suggests, is a final method, and it's cannot be mocked with Mockito.

I try to do this with PowerMokito and it works fine.

import static org.junit.Assert.assertTrue;

import javax.crypto.Cipher;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Cipher.class)
public class SimpleTest {
    @Test
    public void simpleTest() throws Exception {
        Cipher cipher = PowerMockito.mock(Cipher.class);
        PowerMockito.when(cipher.doFinal(null)).thenReturn(null);
        cipher.doFinal(null);
        assertTrue(true);
    }
}

Thanks!

  • 3
    Just a note: the name doFinal() is not named this way because it's final. It's named like that because it does the final encryption operation. It's final because the designer of the class doesn't want that method to be overridable by subclasses. But the two are completely unrelated. Don't expect final methods to have final in their name. – JB Nizet Jul 01 '16 at 10:28
  • I still don't see the point in this exercise. Either you should not test the `Cipher` at all, or you should test your own `CipherSpi` implementstion. – Maarten Bodewes Jul 01 '16 at 12:46