java - 在方法内部使用静态调用设计 Java 单元测试

标签 java spring unit-testing mockito testng

我正在尝试为一个类创建一个单元测试,该类的方法使用来自 apache 的 fluent-hc 库 (http://hc.apache.org/httpcomponents-client-ga/fluent-hc/apidocs/org/apache/http/client/fluent/Request.html) 的 Request.Post 方法。

问题是我不希望它在我每次运行测试套件时都发送实际请求,如果它是单元测试而不是集成测试则更不用说。但我不知道如何解决这个问题。

我是测试领域的新手,根据我读到的大部分时间,当你无法测试某些东西时,类的设计存在问题。

public class HttpRequestSenderServiceImpl implements RequestSenderService {

@Override
public Response sendRequest(String address, String messageBody) throws IOException {
    Request request = Request.Post(address).bodyString(messageBody, ContentType.APPLICATION_JSON);
    Response response = request.execute();

    return response;
}

我使用 Spring 框架和 Spring-Test、Mockito 和 TestNG 作为测试工具。如果您至少能为我指明正确的方向,我将非常感激,可以阅读任何 Material 、书籍、视频等等。我只想学习以正确的方式去做。

我找到了一些解决我的问题的“解决方案”,但它们都使用 PowerMockito,而且我读到的内容对你不利,因为允许模拟静态方法、构造函数等,这会转化为不良的编码实践,即我在这里试图避免什么。

最佳答案

就您的目的而言,问题更多出在 apache 的 fluent-hc Request.Post 中,它是静态的并且不模拟友好,而不是在您的代码中。

您可以使用 Executor和模拟执行方法,或者如果你想使用 Request.Post 将它包装在另一个低级服务接口(interface)中并使用它:

interface RequestSender {
      Response send(String addr,msgBody)
}

class RequestSenderImpl implements RequestSender {
    public Response send(String addr,msgBody) {
       Request request = Request.Post(address).bodyString(messageBody,ContentType.APPLICATION_JSON);
       Response response = request.execute();
       return response;
    }
}

即使没有 mockito,您也可以轻松地模拟代码。

关于java - 在方法内部使用静态调用设计 Java 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47839903/

相关文章:

c# - 这个小方法要进行哪些测试?

python :unit test throws <Response streamed [200 OK]> instead of actual output

java - java Layered Panes中的滚动条问题

Spring “prototype” bean 范围与 “new” 运算符

java - 我可以缩短石膏吗?

java - BeanCreationException : Error creating bean with name 'springApplicationAdminRegistrar' . InstanceAlreadyExistsException

java - 创建类路径资源 META-INF/cxf/cxf.xml 中定义的名称为 'cxf' 的 bean 时出错

unit-testing - Erlang rebar,内核选项

java - 如何在Expression类中使用math.pow()进行计算?

java - 将 JMenuItem 的名称赋予它的 ActionListener