0
import org.junit.Test;
import java.util.Base64;
import org.junit.Assert.*;
import java.util.Random;

...

@Test
public void testEncoding(){
    byte[] data = new byte[32];
    new Random().nextBytes(data);
    String base64 = Base64.getEncoder().encodeToString(data);
    assertEquals(data, Base64.getDecoder().decode(base64));
}

@Test
public void testDecoding(){
    String base64 = "ABCDEFGHIJKLRMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/A==";
    byte[] data = Base64.getDecoder().decode(base64);
    assertEquals(base64, Base64.getEncoder().encodeToString(data));
}

The testEncoding test fails with an AssertionError: Expected :[B@6bf2d08e Actual :[B@5eb5c224 And I can't see why.

theTobias
  • 39
  • 7
  • 2
    Are you sure `assertEquals(byte[], byte[])` does what you want it to? Arrays don't implement equality naturally... – Jon Skeet Jun 21 '16 at 12:45

2 Answers2

2

The flaw is in then Assertion not in the code.

assertEquals will compare the address of the byte array in memory assertArrayEquals will compare the content of the byte array

theTobias
  • 39
  • 7
-1

Try this. You should encode a normal String, and decode a normal String, not a byte-array:

@Test
public void verify() throws Exception {
    String normalString = "ABCDEFGHIJKLRMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/A==";
    byte[] asBytes = normalString.getBytes();
    String encoded = Base64.getEncoder().encodeToString(asBytes);
    byte[] decodedBytes = Base64.getDecoder().decode(encoded);
    String decoded = new String(decodedBytes);

    assertEquals(normalString , decoded);
}
Tom Van Rossom
  • 1,440
  • 10
  • 18
  • I need to encode and decode files to send them in E-Mails and as arguments of HTTP requests. I need this to work with byte arrays or InputStreams, too. Also the method signature of encodeToString requires a byte array. If I use .getBytes() then I still get an assertion error. Expected :[B@50134894 Actual :[B@2957fcb0 – theTobias Jun 21 '16 at 13:01
  • The *object* of base64 encoding is to encode arbitrary binary data as text. – Jon Skeet Jun 21 '16 at 13:05
  • @TomVanRossom What about bytes/byte-sequences that can't be converted to/from your platform's default-encoding? – piet.t Jun 21 '16 at 13:23