DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { public boolean validateObject(Object key, Object obj) { Assert.notNull(this.dirContextValidator, "DirContextValidator may not be null"); Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); Assert.isTrue(obj instanceof DirContext, "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContextType contextType = (DirContextType) key; final DirContext dirContext = (DirContext) obj; return this.dirContextValidator.validateDirContext(contextType, dirContext); } catch (Exception e) { this.logger.warn("Failed to validate '" + obj + "' due to an unexpected exception.", e); return false; } }  ContextSource getContextSource(); void setContextSource(ContextSource contextSource); DirContextValidator getDirContextValidator(); void setDirContextValidator(DirContextValidator dirContextValidator); Object makeObject(Object key); boolean validateObject(Object key, Object obj); void destroyObject(Object key, Object obj);  }
@Test public void testValidateObject() throws Exception { when(dirContextValidatorMock .validateDirContext(DirContextType.READ_ONLY, dirContextMock)) .thenReturn(true); final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); objectFactory.setDirContextValidator(dirContextValidatorMock); final boolean valid = objectFactory.validateObject(DirContextType.READ_ONLY, dirContextMock); assertThat(valid).isTrue(); DirContextValidator secondDirContextValidatorMock = mock(DirContextValidator.class); when(secondDirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock)) .thenThrow(new RuntimeException("Failed to validate")); objectFactory.setDirContextValidator(secondDirContextValidatorMock); final boolean valid2 = objectFactory.validateObject(DirContextType.READ_ONLY, dirContextMock); assertThat(valid2).isFalse(); }