英文:
Testing abstract class with Mockito. How?
问题
以下是翻译好的内容:
我有以下的类:
abstract class Foo {
abstract List<String> getItems();
public void process() {
getItems()
.stream()
.forEach(System.out::println);
}
}
我想要测试的是 process()
方法,但它依赖于抽象的 getItems()
方法。一个解决方案是创建一个临时的模拟类,它继承自 Foo
并实现了这个 getItems()
方法。
在Mockito中,应该如何做呢?
英文:
I have the following class:
abstract class Foo {
abstract List<String> getItems();
public void process() {
getItems()
.stream()
.forEach(System.out::println);
}
}
What I'd like to test is the process()
method, but it is dependent on the abstract getItems()
. One solution can be to just create an ad-hoc mocked class that extends Foo
and implements this getItems()
.
What's the Mockito way to do that?
答案1
得分: 2
为什么不只是:
List<String> customList = ....
Foo mock = Mockito.mock(Foo.class);
Mockito.when(mock.getItems()).thenReturn(customList);
Mockito.when(mock.process()).thenCallRealMethod();
或者(对于void):
doCallRealMethod().when(mock.process()).voidFunction();
英文:
Why not just:
List<String> cutsomList = ....
Foo mock = Mockito.mock(Foo.class);
Mockito.when(mock.getItems()).thenReturn(customList);
Mockito.when(mock.process()).thenCallRealMethod();
Or (for void)
doCallRealMethod().when(mock.process()).voidFunction();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论