模拟类型转换对象



我的bean中有一个简单的方法来处理primefaces数据表中的单元格编辑事件。方法如下:

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());
                     ....
}

我如何嘲笑这个: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);

您需要模拟CellEditEventDatatable:

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);
    }
}

参见:

    <
  • 5文档/gh>

相关内容

  • 没有找到相关文章

最新更新