如何使用 Junit/Mockito 对该 void 方法进行单元测试

发布于 2025-01-21 03:04:39 字数 735 浏览 1 评论 0原文

我有以下空隙方法:

    public void checkInvalidEarlyAccessKey(HippoBean hippoBean, HstRequest hstRequest, HstResponse hstResponse, HttpServletRequest request) {
    if (StringUtils.isNotBlank(hippoBean.getSingleProperty(EARLY_ACCESS_KEY)) && !hippoBean.getSingleProperty(EARLY_ACCESS_KEY).equals(request.getParameter(PARAMETER_KEY))) {
        LOGGER.debug("Early access key is set and null or wrong key is being used. Redirecting to 404 error code");
        hstResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        HstResponseUtils.sendRedirect(hstRequest, hstResponse, ERROR_404_PATH);
    }
}

如何使用Junit/Mockito进行测试?我是否应该测试Hstresponse状态确实是404,以确保if语句是正确的?您能提供一个代码示例吗?最好的做法是什么?

谢谢

I have the following void method:

    public void checkInvalidEarlyAccessKey(HippoBean hippoBean, HstRequest hstRequest, HstResponse hstResponse, HttpServletRequest request) {
    if (StringUtils.isNotBlank(hippoBean.getSingleProperty(EARLY_ACCESS_KEY)) && !hippoBean.getSingleProperty(EARLY_ACCESS_KEY).equals(request.getParameter(PARAMETER_KEY))) {
        LOGGER.debug("Early access key is set and null or wrong key is being used. Redirecting to 404 error code");
        hstResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        HstResponseUtils.sendRedirect(hstRequest, hstResponse, ERROR_404_PATH);
    }
}

How can I test this with Junit/Mockito? Should I test that the hstResponse status is indeed a 404 to ensure the if statement is true? Could you provide a code example? What is the best practice?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝颜夕 2025-01-28 03:04:39

这取决于您的期望。下面的链接包括模拟void方法的有用和批准的答案。您可以开始阅读我提供的链接,并决定您将验证或断言的内容。

如何使用Mockito 模拟Void方法

It depends on what you expect. Below link includes useful and approved answers to mock void methods. You can start to read link I provided and decide what you will verify or assert.

How to mock void methods with Mockito

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文