簡體   English   中英

Java Base64解碼/編碼漫游未得出相同結果

[英]Java Base64 Decoding/Encoding rountrip doesn't come up with same result

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

testEncoding測試失敗,並出現AssertionError:預期:[B @ 6bf2d08e實際:[B @ 5eb5c224而且我不知道為什么。

缺陷在於代碼中沒有斷言。

assertEquals將比較字節數組在內存中的地址assertArrayEquals將比較字節數組的內容

嘗試這個。 您應該編碼一個普通的String,然后解碼一個普通的String,而不是字節數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM