模拟的模拟

时间:2019-01-23 19:09:25

标签: java unit-testing mocking mockito

我正在尝试测试演员表事件:

定义:

private RestAPIAuthenticationFilterMod re;
ServletRequest sRequestMock;
ServletResponse sResponseMock;

@Before
public void setup() {
    re=new RestAPIAuthenticationFilterMod();
    sRequestMock  = Mockito.mock(ServletRequest.class,  withSettings().extraInterfaces(HttpServletRequest.class));
    sResponseMock = Mockito.mock(ServletResponse.class, withSettings().extraInterfaces(HttpServletResponse.class));
}

有问题的线:

 ((HttpServletRequest) request).getHeader("CuentaUsuario");

“请求”是一个模拟,我想生成一个响应“ JMUNOZ”

我尝试了这个,但是它继续执行真实代码:

    @Test
    public void onAccessDeniedNotAuthorizedIsJWTLogInAttemptTest() throws Exception {


    Subject subjectUnderTest = Mockito.mock(Subject.class);

    setSubject(subjectUnderTest);
    when(subjectUnderTest.isAuthenticated()).thenReturn(true);
    when((sRequestMock).getAttribute("whitelisted")).thenReturn(Boolean.TRUE);

    HttpServletRequestWrapper httpMock= Mockito.mock(HttpServletRequestWrapper.class);
    when((httpMock).getHeader("CuentaUsuario")).thenReturn("JMUNOZ");
    when(((HttpServletRequest)sRequestMock).getHeader("CuentaUsuario")).thenReturn("JMUNOZ");
    re.onAccessDenied(sRequestMock, sResponseMock);
}

这是我的SUT:

  protected boolean isUserHostCallAttempt(ServletRequest request, ServletResponse response) {
    try {
        String userName = ((HttpServletRequest) request).getHeader("CuentaUsuario");
        return (userName != null) && (!"".equalsIgnoreCase(userName)) && (isWhiteListed(request));
    } catch (Exception e) {
        log.error(ERROR, e);
    }
    return false;
}


   private boolean isWhiteListed(ServletRequest request) {
    if (null == request.getAttribute("whitelisted")) {
        return false;
    }
    return ((Boolean) request.getAttribute("whitelisted")).booleanValue();
}

解决方案(无断言):

 @Test
public void onAccessDeniedNotAuthorizedIsJWTLogInAttemptTest() throws Exception {
    Subject subjectUnderTest = Mockito.mock(Subject.class);
    setSubject(subjectUnderTest);
    when(subjectUnderTest.isAuthenticated()).thenReturn(true);

    HttpServletRequestWrapper httpMock= Mockito.mock(HttpServletRequestWrapper.class);

    when((httpMock).getAttribute(Mockito.anyString())).thenReturn(Boolean.TRUE);
    when((httpMock).getHeader(Mockito.anyString())).thenReturn("JMUNOZ");
    re.onAccessDenied(httpMock, sResponseMock);
}

谢谢。

1 个答案:

答案 0 :(得分:1)

类型HttpServletRequestWrapper已经扩展了HttpServletRequest,因此您可以直接模拟httpMock.getHeader。不要单独模拟超类型,创建单个模拟并在两个地方使用它。