1
public void doSomething(){
    //...
    HibernateCursorItemReader<Object[]> reader = new HibernateCursorItemReader<>();
    //...
}

how to mock reader, or make new HibernateCursorItemReader<>() return a mock Object?

theAnonymous
  • 1,701
  • 2
  • 28
  • 62
  • Possible duplicate of [How to mock constructor with PowerMockito](https://stackoverflow.com/questions/41110804/how-to-mock-constructor-with-powermockito) – Lino Apr 05 '19 at 07:44
  • There's no way to access reader. Is it possible to make it at least an argument to doSomething to be possible to inject it? – mate00 Apr 05 '19 at 07:45
  • You can use powermock like in the linked potential duplicate to return a completly different object or you can also use `Mockito.spy(reader)`, which allows you to mock certain methods – Lino Apr 05 '19 at 07:46

1 Answers1

1

You can wrap new HibernateCursorItemReader<>(); with a method and mock it instead, e.g.:

 HibernateCursorItemReader<Object[]> getReader() {
      return new HibernateCursorItemReader<>();
 }

 public void doSomething(){
     //...
     HibernateCursorItemReader<Object[]> reader = getReader(); // use method invocation to get a reader
     //...
 }

Now, when you want to mock reader, mock getReader() method instead and return whatever you want:

MyObject object = ...; //your original object

MyObject spyObject = Mockito.spy(object);
Mockito.doReturn(/*your value*/).when(spyObject).getReader();
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28