用Mockito测试抽象类。如何做?

huangapple go评论81阅读模式
英文:

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&lt;String&gt; 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&lt;String&gt; 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();

huangapple
  • 本文由 发表于 2020年10月7日 19:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64243409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定