-1

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

kill-9
  • 104
  • 1
  • 5
  • The answer here is "depends". What you can do: if possible, create a real instance of your bean object, and pass that into the method, along with a (maybe mocked) instance of the HstRequest, and a mock HstResponse. Then verify that the expected method calls occurred on response object. But ideally, if possible: dont use mocks here. When you can use "real" request/response objects, then go with that ... and simply assert that the response object has the expected properties after the call to the method. – GhostCat Apr 12 '22 at 11:26
  • 1
    But note: you learn such things by reading books/tutorials and TRYING things yourself. It is always better to try yourself first, and then maybe ask more experienced people to review your code. – GhostCat Apr 12 '22 at 11:27

1 Answers1

0

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

Alper Derya
  • 237
  • 1
  • 9