Unit test encryption / decryption

I implemented a very simple class called Enigma, which has a symmetric key and two methods: byte[] encryptString(String strToEncrypt)and String decryptBytes(byte[] arrayToDecrypt).

I am trying to write some tests for these methods. I was thinking about testing that the encryption and decryption methods are mutually opposite, but this does not say anything about each of them individually. I wanted to use the methods since they now receive a battery of input outputs and set it up as tests (I know that this is not ideal, but the purpose of these tests is to ensure that the function behaves in the future, as it does today, and not that encryption / decryption is good).

However, I do not know how to get a representation of the output of a byte array on byte[] encryptString(String strToEncrypt), so that I can hard code it in a test class.

Any ideas?

+4
source share
1 answer

A few notes on how to test this (warning of personal opinion :-))

  • If you write unit tests, avoid reading the expected results from the files, as this slows down the testing (unit tests should be very fast), and also create another thing that is not related to your code that may go wrong (i.e. file can be deleted, etc.)
  • , , , . ,
  • , Java - , ( - Java 8, ), ,

(?) . , (, , . SRP). , - .
:

@Test
public void testThatEncryptingStringResultsInExpectedBytes() {
    byte[] encryption = enigma.encryptString(TEST_STRING);

    assertArrayEquals(EXPECTED_ENCRYPTION, encryption);
}

@Test
public void testThatDecryptinEncryptionResultsInOriginalString() {
    String decryption = enigma.decryptBytes(TEST_ENCRYPTION);

    assertEquals(EXPECTED_ORIGINAL_STRING, decryption);
}

@Test
public void testThatDecriptionReversesEncryption() {
    String decryption = enigma.decryptBytes(enigma.encryptString(TEST_STRING));

    assertEquals(TEST_STRING, decryption);
}

@Test
public void testThatEncryptionReversesDecryption() {
    byte[] encryption = enigma.encriptString(enigma.decryptBytes(TEST_ENCRYPTION));

    assertEquals(TEST_ENCRYPTION, encryption);
}

, , , / .

+4

Source: https://habr.com/ru/post/1545723/


All Articles