4

I already managed to stub update():

@Test
public void updateStubbed() {
    UpdatableRecordTest updatableRecordTest = spy(new UpdatableRecordTest());
    doReturn(1).when(updatableRecordTest).update();
}

However, when I try to stub store():

@Test
public void storeStubbed() {
    UpdatableRecordTest updatableRecordTest = spy(new UpdatableRecordTest());
    doReturn(1).when(updatableRecordTest).store();
}

I get the error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Integer cannot be returned by fieldsRow() fieldsRow() should return Row


If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because:

  1. This exception might occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
    • with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

How to stub store() method?

Haruki
  • 674
  • 1
  • 9
  • 24
  • 1
    I have the same problem. Apparently it's impossible to mock `final` methods (such as `store()` with mockito unless you use mockito v2 and add special extension. – Leukonoe Sep 06 '18 at 15:30

1 Answers1

1

You cannot mock store() method with Mockito as it is a final method, and Mockito doesn't provide support for mocking final methods. What you can do, is:

  • for unit tests, use PowerMock (which provides a way of mocking final methods, but is not Spring friendly. Just mentioning in case you work with Spring),
  • for functional tests, create embedded DB schema, and configure your JOOQ to use this one in testing environment.

Unfortunately I don't have a better answer.

Leukonoe
  • 649
  • 2
  • 10
  • 29
  • This is actually supported with a little extra help: https://stackoverflow.com/questions/14292863/how-to-mock-a-final-class-with-mockito/40018295#40018295 – JamesD Aug 21 '20 at 20:01