我必须建立一个接口.要测试我需要覆盖3个接口方法.我搜索了一些例子但是找不到有用的东西并且很好地解释了.我对Mocking Framework没有偏好,只是建议最适合我的用例.
我需要保留此功能,并且不希望有400行未使用的覆盖.
public class StubInventory implements Inventory
{
private final ItemStack[] contents;
public StubInventory (int size)
{
contents = new ItemStack[size];
}
@Override
public void setItem (int index, ItemStack item)
{
contents[index] = item;
}
@Override
public ItemStack getItem (int index)
{
return contents[index];
}
@Override
public void clear ()
{
Arrays.fill(contents, null);
}
//<-- Insert 400 lines of unused @Override's here
}
Run Code Online (Sandbox Code Playgroud)
更新:
我的代码使用getter,尤其是setter,并且必须工作.这些值未预定义.这些值将由我的代码设置,我的测试代码将验证结果.
mockInventory = mock(Inventory.class);
//Not "nice" but will probably work
for (int i = 0; i < size * 9; i++)
when(mockInventory.getItem(i)).thenReturn(contents[i]);
//This is where the problem is. I need to take item (ItemStack)
// and set it in my stubbed class. Basically I need to access the parameter.
for (int i = 0; i < size * 9; i++)
when(mockInventory.setItem(i, item)).then(contents[i] = item);
Run Code Online (Sandbox Code Playgroud)
all*_*rog 10
试试Mockito.对于大多数情况来说,它非常稳定和方便.例如,你可以写:
Inventory inventory = Mockito.mock(Inventory.class);
Mockito.when(inventory.getItem(Mockito.any())).thenReturn(somePresetItemStack);
Run Code Online (Sandbox Code Playgroud)
您应该在Mockito.*方法上使用静态导入以获得更好的可读性:
import static org.Mockito.*;
Run Code Online (Sandbox Code Playgroud)