Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking type-casting objects

I have a simple method in my bean to handle cell edit event in primefaces datatable. Method looks like this:

public void onCellEdit(CellEditEvent event) {
    Object oldValue = event.getOldValue();
    Object newValue = event.getNewValue();

    User user = (User) ((DataTable) event.getComponent()).getRowData();
    if (!newValue.equals(oldValue))
    user.setUsername(oldValue.toString());
                     ....
}

How do I mock this: User user = (User) ((DataTable) event.getComponent()).getRowData();

like image 272
gmode Avatar asked Sep 17 '15 11:09

gmode


2 Answers

CellEditEvent mockEvent = Mockito.mock(CellEditEvent.class);
DataTable mockDataTable = Mockito.mock(DataTable.class);

Mockito.when(mockEvent.getComponent()).thenReturn(mockDataTable);
Mockito.when(mockDataTable.getRowData()).thenReturn(userObj);
like image 158
kswaughs Avatar answered Nov 20 '22 17:11

kswaughs


You need to mock both the CellEditEvent and the Datatable:

public class EventTest {

    //Let's supose that's the managed bean you want to test
    public class Bean {
        public void onCellEdit(CellEditEvent event) {
            User user = (User) ((DataTable) event.getComponent()).getRowData();
            System.out.println(user);
        }
    }

    @Test
    public void test() {
        Bean bean = new Bean();
        CellEditEvent evt = Mockito.mock(CellEditEvent.class);
        DataTable table = Mockito.mock(DataTable.class);
        User user = new User();
        user.setName("Bob");
        Mockito.when(table.getRowData()).thenReturn(new User("Username"));
        Mockito.when(evt.getComponent()).thenReturn(table);
        bean.onCellEdit(evt);
    }
}

See also:

  • Mockito documentation
like image 24
Xtreme Biker Avatar answered Nov 20 '22 18:11

Xtreme Biker