我试图对我的代码运行Unit测试,有一个测试失败了,当我更深入的时候,我注意到Base64.decode()总是在测试环境中返回null。我的具体案例是:
测试方法
public String decode(String jwt){
System.out.println(jwt); //eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
byte[] data = Base64.decode(jwt, Base64.DEFAULT);
return new String(data, "UTF-8"); //null pointer exception - data = null
}测试本身:
@Test
public void validateBase64Decode() {
String stringToTest = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9";
String expectedResult = "{\"sub\": \"1234567890\", \"name\": \"John Doe\", \"admin\": true}";
Assert.assertEquals(Util.decode(stringToTest), expectedResult);
}由于空指针异常,测试总是失败:
java.lang.NullPointerException
at java.lang.String.<init>(String.java:481)因此,我进一步发现,测试环境中的任何字符串都无法解码:
@Test
public void validateBase64Decode() {
Assert.assertNotNull(Base64.decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9", 0));
} //Test NEVER passes - assertion error拜托,这里有古鲁吗?怎么了?提前感谢
发布于 2016-07-05 08:32:48
刚刚用机器人测试了它的工作:
public void testValidateBase64Decode() throws InterruptedException {
assertTrue("EcoScoreTesterActivity Activity never started", solo.waitForActivity(MainMenuActivity.class, WAIT_FOR_ACTIVITY_TIMEOUT));
String stringToTest = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9";
String expectedResult = "{\"sub\": \"1234567890\", \"name\": \"John Doe\", \"admin\": true}";
//The string decode is different as yours
expectedResult = "{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"admin\":true}";
assertNotNull(Base64.decode(stringToTest, 0));
String result = new String(Base64.decode(stringToTest, 0));
//Show in logcat result of decoding
Log.i("Test-Decoding","result+":result);
assertTrue("Error decoding", result.equals(expectedResult));
}在你看来,它应该是这样的:
public void testvalidateBase64Decode() {
String stringToTest = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9";
String expectedResult = "{\"sub\": \"1234567890\", \"name\": \"John Doe\", \"admin\": true}";
//The string decode is different as yours
expectedResult = "{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"admin\":true}";
String result = new String(Base64.decode(stringToTest, 0));
//Show in logcat result of decoding
Log.i("Test-Decoding","result+":result);
Assert.assertTrue("Error decoding", result.equals(expectedResult));
}我检查这两个选项,它在我的工作空间中工作
发布于 2017-12-13 07:11:47
在gradle编译组中添加以下内容:'commons-codec',name:'commons-codec',version:'1.9',并通过导入使用此方法
import org.apache.commons.codec.binary.Base64
new String(Base64.encodeBase64(inData))
Base64.decodeBase64(inString.getBytes())https://stackoverflow.com/questions/38198256
复制相似问题