单元测试基本身份验证

时间:2017-04-25 09:24:02

标签: java android unit-testing basic-authentication

我对单元测试我的身份验证方法有一些问题。这是我的方法:

    public int basicAuth(String username, String password) throws IOException {
    connection = (HttpURLConnection)new URL("URL").openConnection();
    connection.setRequestMethod("GET");
    String basicAuth = username + ":" + password;
    String wrap = "Basic " + new String(Base64.encode(basicAuth.getBytes(),Base64.NO_WRAP));
    connection.setRequestProperty("Authorization",basicAuth);
    connection.connect();
    //InputStream in = connection.getInputStream();
    int response = connection.getResponseCode();
    Log.v("Reponse HTTP : ", String.valueOf(response));
    responseCode_ = connection.getResponseCode();
    return responseCode_;
}

这是我的测试代码:

@Test
public void basicAuth() throws Exception {
    PowerMockito.mockStatic(Base64.class);
    String username = "username";
    String password = "password";
    int responseCode = 200;
    int integer = auth.basicAuth(username, password);
    assertEquals(responseCode, integer);
}

我正在使用Powermock,因为我的Base64错误并没有被嘲笑。现在,当我使用Powermock时,我有这个错误:

  

显示java.lang.NullPointerException       在java.lang.String。(String.java:566)       在com.example.local.app_android.Authentification.basicAuth(Authentification.java:96)       在com.example.local.app_android.AuthentificationTest.basicAuth(AuthentificationTest.java:34)       /.../       at java.lang.reflect.Method.invoke(Method.java:498)       在com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

(我已经删除了错误的中间部分)

有人知道错误的来源吗?

编辑N°1

testCompile 'org.powermock:powermock-api-mockito:1.6.1'
testCompile 'org.powermock:powermock-module-junit4-rule-agent:1.6.1'
testCompile 'org.powermock:powermock-module-junit4-rule:1.6.1'
testCompile 'org.powermock:powermock-module-junit4:1.6.1'
testCompile 'org.mockito:mockito-core:1.10.19'

2 个答案:

答案 0 :(得分:1)

真正的答案是:你不应该编写那么难以使用PowerMock来测试它的代码。

含义:通过使用 static ,您创建了难以测试的代码。相反:学习如何编写易于测试的代码(例如,启动here)。

然后重构你的代码,以避免静态调用;例如,通过将encode()方法包装到一个微小的包装器接口中(顺便说一句,您仍然可以使用这些静态方法实现接口)。

如上所述;真正的答案是避免模拟静态调用;从而避免使用PowerMock。除此之外;使用PowerMock模拟静态调用工作正常;您只需按照PowerMock人员所述的确切recipe进行操作。

要明确这一点:您仍然需要查看解决方案的具体细节;用户查尔斯沃思已经在你的代码中预测了下一个NPE问题(而且他通常是现货)。

答案 1 :(得分:0)

实际上你错过了期望:

Base64.encode(basicAuth.getBytes(),Base64.NO_WRAP)

返回null,这解释了为什么String的构造函数抛出NPE。

您还应该查看文档,特别是因为您应该使用重播并验证何时使用模拟而不是(这意味着您没有测试模拟被调用):https://github.com/powermock/powermock/wiki/MockStatic