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)
Expected behavior Java test runs fine and the header() method can be mocked
To Reproduce
- 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>
- create the file
resources/mockito-extensions/org.mockito.plugins.MockMakerwith the contentmock-maker-inlineso that final Kotlin classes can be mocked - 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);
}
- 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
- Use custom build Fixing tipsy/javalin#979 — committed to Zemke/javalin-chess by Zemke 4 years ago
This will be fixed soon: https://github.com/tipsy/javalin/pull/1162
A suggestion (
Mockito.<String>when(context.header("Authorization")).thenReturn(test1);) was recently posted in mockito/mockito#1943, might be worth a shot.