【发布时间】:2017-12-20 17:54:34
【问题描述】:
我想测试我的方法,我需要模拟 Items 和 Rows 的向量来遍历它们。
当我从 Item 类(在测试中)调用 getRows() 时,我准备了我希望得到的结果向量。
问题是在测试中getRows方法的结果总是空的,所以这意味着doReturn语句在这里没有正常工作。
我有什么不对吗?
class MyServiceTest {
@Mock
private Item mockedItem;
@Mock
private Row mockedRow;
@InjectMocks
@Spy
private MyService myService;
@Test
public void testMyMethod() {
Vector<Row> rows = new Vector<Row>();
Row row = new Row();
rows.add(row);
doReturn(rows).when(mockedItem).getRows();
...
//some code to test the service
}
}
class MyService {
protected SomeObject myMethod(Vector<Item> items) {
for(Item item : items) {
for(Row row : item.getRows()) {
//cannot get here while debugging the test
//some code
}
}
...
}
}
class Item {
...
public Vector<Row> getRows(){
//return some vector of rows
}
}
【问题讨论】:
-
可以分享一下使用
mockedItem的测试代码吗?我宁愿怀疑它不在模拟服务中,而不是doReturn不起作用。 -
能不能也把
Row类的代码显示一下。 -
我不确定我是否理解正确,但它没有在任何地方使用。在 doReturn 之后,我只调用服务,然后执行断言。
-
@StefanBirkner 没有什么特别之处——它只是创建了一些值的列表。无论如何,我期待 doReturn 根本不调用方法 getRows 并且应该总是返回相同的向量。我错了吗?
-
myMethod() 在哪里调用?您需要显示更多 MyService 类。因为我怀疑你没有正确注入模拟项目
标签: java testing junit mocking mockito