Search code examples
javaunit-testingeasymocksecurityexception

EasyMock to test SecurityException


I am trying to use easyMock to write a test, that tests SecurityException in the following code.

eg. for NumberFormatException I use the below.

EasyMock.expect(mockEntityManager.find(UserProfile.class,"abc")).andThrow(new NumberFormatException());

Any ideas on what to expect to throw SecurityException?

public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {

EntityManager entityManager = (EntityManager)Component.getInstance("entityManager");

  if (s == null || s.equals("null")) {
        return null;      } else {
        try {
            long i = Long.parseLong(s);
            return entityManager.find(UserProfile.class, i);
        } catch (NumberFormatException e) {
            logger.error(e);
        } catch (SecurityException e) {
            logger.error(e);
        }         }

    return null;  }

Solution

  • Thanks for your responses..here is what I did to expect SecurityException.

    MyClass abc = new MyClass();
    
    EasyMock.expect(mockEntityManager.find(MyClass.class,111L)).andThrow(new SecurityException());
    
    EasyMock.replay(mockEntityManager);
    
    Object target = abc.getAsObject(mockFacesContext, mockUiComponent,"111");
    
    Assert.assertEquals(null, target);