2

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?

IsaacLevon
  • 2,260
  • 4
  • 41
  • 83
  • 1
    I would not *mock* `Foo` but create an inner class `FooTestImpl` in your `FooTest` class and use an instance of that for your test. You should of course not override any methods already implemented in the parent class. – luk2302 Oct 07 '20 at 11:53
  • 2
    Does this answer your question? [Using Mockito to test abstract classes](https://stackoverflow.com/questions/1087339/using-mockito-to-test-abstract-classes) – Ivar Oct 07 '20 at 11:57

1 Answers1

2

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();
Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121