我目前正在为我的selenium项目编写单元测试,我正在使用Mockito来模拟我的物品和驱动程序。
我遇到的问题是我有一个功能,用于更改单选按钮列表中的单选选项,但我遇到了问题。代码如下所示:
@Test
public void testChangeRadioState(){
WebElement mockElement = mock(WebElement.class);
List<WebElement> mockElementList = new ArrayList<>();
WebElement selectedMockElement = mock(WebElement.class);
/*The when statements*/
when(selectedMockElement.isSelected()).thenReturn(true);
doReturn(when(mockElement.isSelected()).thenReturn(true)).when(mockElement).click();
doReturn(when(selectedMockElement.isSelected()).thenReturn(false)).when(mockElement).click();
/*Add a selected and a none selected element to the list*/
mockElementList.add(mockElement);
mockElementList.add(selectedMockElement);
/*The method that is beeing tested*/
elementSetter.changeRadioState(mockElementList);
Assert.assertTrue("The radio state was not selected",mockElement.isSelected());
}
我正在尝试做什么?返回部分是告诉元素“mockElement”,当它收到点击时,它应该在isSelected()调用时始终返回true。但由于Click()是一个无效函数,它不会让我这样做。有人知道解决这个问题吗?
答案 0 :(得分:1)
好的,这是一个单独的主题 - 你正在测试什么,我会嘲笑这么深的东西。
我会像这样重写测试:
@Test
public void testChangeRadioState() {
WebElement mockElement = mock(WebElement.class);
WebElement selectedMockElement = mock(WebElement.class);
List<WebElement> mockElementList = new ArrayList<>();
/*The when statements*/
when(selectedMockElement.isSelected()).thenReturn(true);
// By default mockito will return false but maybe I want to highlight
// that this is important
when(mockElement.isSelected()).thenReturn(false);
/*Add a selected and a none selected element to the list*/
mockElementList.add(mockElement);
mockElementList.add(selectedMockElement);
/*The method that is beeing tested*/
elementSetter.changeRadioState(mockElementList);
verify(selectedMockElement).click();
// according to test method name I would add
// one more verification that something was dis-selected
}
我认为另一种具有状态的变体有不必要的模拟:
boolean selected;
@Test
public void testChangeRadioState() {
selected = false;
WebElement mockElement = mock(WebElement.class);
WebElement selectedMockElement = mock(WebElement.class);
List<WebElement> mockElementList = new ArrayList<>();
/*The when statements*/
when(selectedMockElement.isSelected()).thenReturn(true);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) {
selected = true;
return null;
}
}).when(mockElement).click();
/*Add a selected and a none selected element to the list*/
mockElementList.add(mockElement);
mockElementList.add(selectedMockElement);
/*The method that is beeing tested*/
elementSetter.changeRadioState(mockElementList);
Assert.assertTrue("The radio state was not selected", selected);
// according to test method name I would add
// one more verification that something was dis-selected
}
但同样,名字也有误导性。例如,我希望当点击时,有些元素不会被选中。再次询问您正在测试的内容