javalin: Mockito fails for reified kotlin methods in Java tests

Actual behavior (the bug) Running simple unit tests on Java with Mockito fails when mocking the .header() method of class Context.kt. Apparently Mockito can not choose the correct method to mock. This behavior is not 100% reproducible, it fails for 90% of the time but runs fine in roughly 10% of the time. A user on Stackoverflow was able to reproduce the issue as well.

Exception:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 

String cannot be returned by header()
header() should return Validator
***
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.

    at my.package.stupidTest1(JavalinTest.java:28)

More info: https://stackoverflow.com/questions/61792392/final-kotlin-class-can-not-be-mocked-because-method-should-return-validator

Expected behavior Java test runs fine and the header() method can be mocked

To Reproduce

  1. set up Mockito in a java project
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>3.2.0</version>
  <scope>test</scope>
</dependency>
  1. create the file resources/mockito-extensions/org.mockito.plugins.MockMaker with the content mock-maker-inline so that final Kotlin classes can be mocked
  2. create a test class with a single test method:
 @Test
  void stupidTest1() {
    Context context = mock(Context.class);

    String test1 = "hello123";
    when(context.header("Authorization")).thenReturn(test1);
  }
  1. run mvn tests, it should fail almost every time with the exception shown above

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 21 (13 by maintainers)

Commits related to this issue

Most upvoted comments

A suggestion (Mockito.<String>when(context.header("Authorization")).thenReturn(test1);) was recently posted in mockito/mockito#1943, might be worth a shot.