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();
CellEditEvent mockEvent = Mockito.mock(CellEditEvent.class);
DataTable mockDataTable = Mockito.mock(DataTable.class);
Mockito.when(mockEvent.getComponent()).thenReturn(mockDataTable);
Mockito.when(mockDataTable.getRowData()).thenReturn(userObj);
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With