我正在尝试对我的代码运行单元测试,并且一次测试失败,当我深入时,我注意到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)
因此我进一步发现测试环境中的任何String都无法解码:
@Test
public void validateBase64Decode() {
Assert.assertNotNull(Base64.decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9", 0));
} //Test NEVER passes - assertion error
拜托,这里有任何大师吗?怎么了 ?提前致谢
答案 0 :(得分:0)
刚刚测试了robotium及其工作原理:
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));
}
我只检查两个选项,并且它在我的工作区中工作
答案 1 :(得分:0)
在gradle编组中添加:'commons-codec'
,名称:'commons-codec'
,版本:'1.9'
并通过导入
import org.apache.commons.codec.binary.Base64
new String(Base64.encodeBase64(inData))
Base64.decodeBase64(inString.getBytes())