首页 > 解决方案 > 无法在 Junit/Mockito 中模拟值

问题描述

我有这个用于登录的身份验证方法,我正在对其进行 junit 测试。

我正在使用 Mockito、spring4、hibernate5。

我面临的是这个。

junit 测试结果对testIsAuthorizedUser_normalLogin(). 然而testIsAuthorizedUser_blackListUser(),它不是。

我期待它抛出一个异常。

问题在于这行代码。

when(blacklistDeviceService.getBlacklistDeviceForSearch(
            eq(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal()), eq(request.getRemoteAddr()), eq(true), eq(null), eq(null), eq(null)))
        .thenReturn(deviceListForIp);

当我调试代码时,我blacklistDeviceService.getBlacklistDeviceForSearch没有返回我强制它返回的对象。相反,它返回给我一个空列表。

我如何返回值?

主要实现

public Map<String,String> isAuthorizedUser(String username, String password, Integer loginType, String imei, HttpServletRequest req) throws ErrorException
{
    HashMap<String,String> result = new HashMap<>();

    UUID uuid  = UUID.randomUUID();     

    UserInfo user = null;       

    user = isAuthorizedUser(username, password, loginType, imei, req, uuid.toString());

    if (isPolicyEnforce)
    {
        validate(user);

        //trigger when user pwd is expired or when password is reset
        if (user.getExpire() || user.getIsPasswordReset())
        {
            result.put(PropertiesUtil.MAPPING_TOKEN, generateToken(user, uuid.toString()));
            result.put(PropertiesUtil.MAPPING_CHANGE_PASSWORD, "true");

            return result;
        }
    }

    result.put(PropertiesUtil.MAPPING_TOKEN, generateToken(user, uuid.toString()));
    result.put(PropertiesUtil.MAPPING_CHANGE_PASSWORD, "false");        

    return result;
}

private UserInfo isAuthorizedUser(String username, String password, Integer loginType, String imei, HttpServletRequest req, String uuid) throws ErrorException
{   
    UserInfo user = userInfoDAO.findById(username);

    if (GlobUtil.isNotEmpty(user))
    {           
        try
        {
            if (isPolicyEnforce && (maxFailAttempt < 0))
            {
                throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_POLICY));
            }

            Set<Role> roles = new HashSet<>(userRoleDAO.getRoleBy(user));

            if(roles.isEmpty())
            {
                throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_UNAUTHORIZED_USER));
            }

            if (PasswordEncoder.verifyPassword(password, user.getPassword()))
            {                   
                if(isBlacklist(req.getRemoteAddr(), imei))
                {
                    throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_UNAUTHORIZED_DEVICE));
                }

                if(GlobUtil.isNotEmpty(user.getErrorCount()) && user.getErrorCount() > 0)
                {                       
                    user.setErrorCount(0);
                    accessControlTransNewService.transNewUpdateUser(user);
                }

                accessControlTransNewService.transNewAddLoginLog(username, PropertiesUtil.ACTION_LOGIN, PropertiesUtil.getEnum(PropertiesUtil.LoginType.values(), loginType).name(), "Login - Success.", req);
            }
            else
            {
                if (user.getIsActive() && !user.getIsLock())
                {
                    accessControlTransNewService.transNewAddLoginLog(username, PropertiesUtil.ACTION_LOGIN, PropertiesUtil.getEnum(PropertiesUtil.LoginType.values(), loginType).name(), "Login - Fail. Invalid password.", req);

                    unauthorizedAccess(user, maxFailAttempt);

                    throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_USERPWD));
                }
                else
                {
                    throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INACTIVE_USER));
                }
            }
        }
        catch (CannotPerformOperationException | InvalidHashException e)
        {
            throw new ErrorException(e);
        }   
        catch (NumberFormatException nfe)
        {
            throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_POLICY));
        }
    }
    else
    {
        accessControlTransNewService.transNewAddLoginLog(username, PropertiesUtil.ACTION_LOGIN, PropertiesUtil.getEnum(PropertiesUtil.LoginType.values(), loginType).name(), "Login - Fail. User do not exist.", req);

        throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_USERPWD));
    }

    addUserToSession(user, req, uuid);

    return user;
}


private boolean isBlacklist(String ipAddress, String imei)
{
    List<BlacklistDevice> deviceListForImei = new ArrayList<>();
    List<BlacklistDevice> deviceListForIp = new ArrayList<>();

    if(GlobUtil.isNotEmpty(imei))
    {
        deviceListForImei = blacklistDeviceService.getBlacklistDeviceForSearch(PropertiesUtil.BlacklistType.IMEI.ordinal(), imei, true, null, null, null);      
    }

    if(GlobUtil.isNotEmpty(ipAddress))
    {
        deviceListForIp = blacklistDeviceService.getBlacklistDeviceForSearch(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal(), ipAddress, true, null, null, null);     
    }

    return (!deviceListForImei.isEmpty()) || (!deviceListForIp.isEmpty());
}

嘲笑

@Before
public void setUp() throws Exception
{
    MockitoAnnotations.initMocks(this);

    user = new UserInfo("user1", "sha1:64000:18:VFNOK/vZ3W8Zd9/xDQKUBNlccvpmydbu:rlemV/kvTi/FNZpEA/9jf+Wh", "User 1", "User 1",
            "User 1",0, true,false, new Date(), false, null, false, false);

    roles = new ArrayList<>();

    roles.add(new Role("ADMIN","ADMIN"));

    deviceListForImei = new ArrayList<>();

    deviceListForIp = new ArrayList<>();

    BlacklistDevice blacklistDevice = new BlacklistDevice(1, "Blacklist", PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal(), "192.168.1.100", "admin", new Date(), true);
    deviceListForIp.add(blacklistDevice);
}

/**
 * Test method for
 * {@link com.stengg.stee.auth.service.impl.AccessControlServiceImpl#isAuthorizedUser(java.lang.String, java.lang.String, java.lang.Integer, java.lang.String, javax.servlet.http.HttpServletRequest)}.
 */
@Test
public void testIsAuthorizedUser_normalLogin()
{
    MockHttpServletRequest request = new MockHttpServletRequest();

    String username = "user1";
    String password = "password";
    Integer loginType = PropertiesUtil.LoginType.IPAC2.ordinal();
    String imei = "";

    when(userInfoDAO.findById(anyString())).thenReturn(user);
    when(userRoleDAO.getRoleBy(any(UserInfo.class))).thenReturn(roles);
    when(blacklistDeviceService.getBlacklistDeviceForSearch(anyInt(), anyString(), anyBoolean(), anyInt(), anyInt(), anyString())).thenReturn(Collections.EMPTY_LIST);
    doNothing().when(accessControlTransNewService).transNewAddLoginLog(anyString(), anyString(), anyString(), anyString(), any(HttpServletRequest.class));

    when(onlineUsers.getOnlineUser(anyString())).thenReturn(null);
    when(blueForceTrackerStore.removeViewer(anyString())).thenReturn(false);

    Map<String, String> result1 = accessControlService.isAuthorizedUser(username, password, loginType, imei, request);

    //login success
    assertNotNull(result1);
    assertNotNull(result1.get("token"));
    assertNotNull(result1.get("token").contains("Bearer "));
}

@Test(expected = ErrorException.class)
public void testIsAuthorizedUser_blackListUser()
{
    MockHttpServletRequest request = new MockHttpServletRequest();

    String username = "user1";
    String password = "password";
    Integer loginType = PropertiesUtil.LoginType.IPAC2.ordinal();
    String imei = "";

    when(userInfoDAO.findById(anyString())).thenReturn(user);
    when(userRoleDAO.getRoleBy(any(UserInfo.class))).thenReturn(roles);
    when(blacklistDeviceService.getBlacklistDeviceForSearch(
            eq(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal()), eq(request.getRemoteAddr()), eq(true), eq(null), eq(null), eq(null)))
        .thenReturn(deviceListForIp);
    doNothing().when(accessControlTransNewService).transNewAddLoginLog(anyString(), anyString(), anyString(), anyString(), any(HttpServletRequest.class));

    when(onlineUsers.getOnlineUser(anyString())).thenReturn(null);
    when(blueForceTrackerStore.removeViewer(anyString())).thenReturn(false);

    Map<String, String> result2 = accessControlService.isAuthorizedUser(username, password, loginType, imei, request);

    assertNull(result2);
}

标签: springhibernatejunitmockito

解决方案


您可能想要使用另一个构造:

        doReturn(deviceListForIp)
     .when(blacklistDeviceService)
.getBlacklistDeviceForSearch(eq(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal()), eq(request.getRemoteAddr()), eq(true), eq(null), eq(null), eq(null))

空列表是未正确模拟行为的标志,它的默认值。


推荐阅读