java - 如何使用 JUnit 和 Mockito 来模拟内部逻辑

标签 java unit-testing junit mockito

我对 Junit 和 Mockito 有点陌生,试图了解如何模拟类的部分逻辑。

我有一个执行 http post 和 get 调用的方法,但它可能是数据库查找。如何在此方法中模拟 HTTP 调用的响应

  BufferedReader in = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}

我的意思是必须有一种方法来测试我的逻辑,而无需进行真正的http调用或数据库查找或其他任何操作。

// HTTP GET request
public String sendGet(URL url) throws Exception {

    s_logger.debug("URL: " + url);
    HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();

    // Add request header
    httpsConnection.setRequestMethod("GET");
    httpsConnection.setRequestProperty("Content-Type", "application/xml");

    if (sessionId != null) {
        httpsConnection.setRequestProperty("sessionId", sessionId);
    } else {
        httpsConnection.setRequestProperty("username", ACCOUNT_USERNAME);
        httpsConnection.setRequestProperty("password", ACCOUNT_PASSWORD);
    }

    httpsConnection.setInstanceFollowRedirects(false);
    httpsConnection.setUseCaches(false);

    // Print Request Header
    s_logger.debug("Request Header: " + httpsConnection.getRequestProperties());

    int responseCode = httpsConnection.getResponseCode();
    s_logger.debug("Response Code : " + responseCode);

    Map<String, List<String>> headerFields = httpsConnection.getHeaderFields();
    s_logger.debug("Response Header: " + headerFields);

    BufferedReader in = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // Set Session ID
    final String SESSION_KEY = "sessionId";
    if (this.sessionId == null && httpsConnection.getHeaderFields().containsKey(SESSION_KEY)) {
        this.sessionId = httpsConnection.getHeaderFields().get(SESSION_KEY).get(0);
        s_logger.debug("SESSION ID : " + this.sessionId);
    }

    // print result
    s_logger.debug("RESPONSE: " + response.toString());
    return response.toString();
}

感谢您的任何帮助或建议。

更新: 我确实做了一些建议,但我不确定这是否有意义,而且我也不喜欢这些方法现在公开的事实。

    final URL url = new URL("https://test.com");
    final String request = "Test";
    HttpsURLConnection httpsConnection = mock(HttpsURLConnection.class);


    final HttpConnectionClient httpSpy = spy(new HttpConnectionClient());
    Mockito.doReturn(httpsConnection).when(httpSpy).getConnection(url);
    Mockito.doNothing().when(httpSpy).sendRequest(httpsConnection, request);
    Mockito.doReturn(response).when(httpSpy).createBufferReader(httpsConnection);

    assertEquals(response,httpSpy.sendPost(url, request));

最佳答案

一种黑客方法是使用 spy 和包本地方法:

public  class MyClass {
     public void myMethod() {
         //stuff
         stuffThatNeedsStubbing();
         //more stuff
     }

     void stuffThatNeedsStubbing() {
         //stuff that needs stub
     }
}

public class MyClassTest {
    @Test
    public void example() {
        final MyClass myClass = spy(new MyClass());
        doNothing().when(myClass).stuffThatNeedsStubbing();
        myClass.myMethod();
    }
}

在您的情况下,您可以创建一个包本地方法 BufferedReader createBufferedReader(),并在测试中将其替换为模拟。

关于java - 如何使用 JUnit 和 Mockito 来模拟内部逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936063/

相关文章:

node.js - sinon stub 在 Node.js 测试中不起作用

unit-testing - TDD 与函数式编程语言相比如何?

c# - 无法从 appSettings 读取

spring - MockMvc 返回 null 而不是对象

java - JUnit - 方法之前

java - 如何获取从Excel工作表中选中的复选框值

Java:前缀 - 后缀问题

java - 如何使用eclipse生成多个包的可执行jar文件

javascript - 选择窗口无法选择子窗口

java - 如何对 LinkedHashMap 中的重复键值求和?