模拟类型转换对象

时间:2015-09-17 11:07:38

标签: java jsf primefaces mocking mockito

我的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();

2 个答案:

答案 0 :(得分:4)

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

Mockito.when(mockEvent.getComponent()).thenReturn(mockDataTable);
Mockito.when(mockDataTable.getRowData()).thenReturn(userObj);

答案 1 :(得分:3)

您需要模拟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);
    }
}

另见: