question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mockito spying on kotlin class error

See original GitHub issue

Hello. I am getting error with a version of Mockito exactly from 2.6.7 (in 2.7.19 reproduced) (in 2.6.6 not reproduced) With a version of Mockito 2.2.9 my code is working. Seems something wrong with parsing while mocking, see a stacktrace:

org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class com.example.myapplication.Samples.`
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
Java               : 1.8
JVM vendor name    : JetBrains s.r.o
JVM vendor version : 25.112-b06
JVM name           : OpenJDK 64-Bit Server VM
JVM version        : 1.8.0_112-release-b06
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.12.3
Underlying exception : java.lang.IllegalArgumentException: Could not create type

	at com.example.mayudin.myapplication.ExampleUnitTest.addition_isCorrect(ExampleUnitTest.kt:22)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.IllegalArgumentException: Could not create type
	at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:140)
	at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
	at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
	at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
	at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
	at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
	at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
	at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:26)
	at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
	at org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
	at org.mockito.Mockito.spy(Mockito.java:1812)
	... 28 more
Caused by: java.lang.reflect.GenericSignatureFormatError: Signature Parse error: expected '<' or ';' but got .
	Remaining input: .SampleDelegate<TT;>;
	at sun.reflect.generics.parser.SignatureParser.error(SignatureParser.java:124)
	at sun.reflect.generics.parser.SignatureParser.parsePackageNameAndSimpleClassTypeSignature(SignatureParser.java:348)
	at sun.reflect.generics.parser.SignatureParser.parseClassTypeSignature(SignatureParser.java:310)
	at sun.reflect.generics.parser.SignatureParser.parseFieldTypeSignature(SignatureParser.java:289)
	at sun.reflect.generics.parser.SignatureParser.parseFieldTypeSignature(SignatureParser.java:283)
	at sun.reflect.generics.parser.SignatureParser.parseTypeSignature(SignatureParser.java:485)
	at sun.reflect.generics.parser.SignatureParser.parseReturnType(SignatureParser.java:627)
	at sun.reflect.generics.parser.SignatureParser.parseMethodTypeSignature(SignatureParser.java:577)
	at sun.reflect.generics.parser.SignatureParser.parseMethodSig(SignatureParser.java:171)
	at sun.reflect.generics.repository.ConstructorRepository.parse(ConstructorRepository.java:55)
	at sun.reflect.generics.repository.ConstructorRepository.parse(ConstructorRepository.java:43)
	at sun.reflect.generics.repository.AbstractRepository.<init>(AbstractRepository.java:74)
	at sun.reflect.generics.repository.GenericDeclRepository.<init>(GenericDeclRepository.java:49)
	at sun.reflect.generics.repository.ConstructorRepository.<init>(ConstructorRepository.java:51)
	at sun.reflect.generics.repository.MethodRepository.<init>(MethodRepository.java:46)
	at sun.reflect.generics.repository.MethodRepository.make(MethodRepository.java:59)
	at java.lang.reflect.Method.getGenericInfo(Method.java:102)
	at java.lang.reflect.Method.getGenericReturnType(Method.java:255)
	at net.bytebuddy.description.type.TypeDescription$Generic$LazyProjection$ForLoadedReturnType.resolve(TypeDescription.java:5656)
	at net.bytebuddy.description.type.TypeDescription$Generic$LazyProjection.accept(TypeDescription.java:5297)
	at net.bytebuddy.description.method.MethodDescription$TypeSubstituting.getReturnType(MethodDescription.java:1320)
	at net.bytebuddy.description.method.MethodDescription$AbstractBase.asSignatureToken(MethodDescription.java:704)
	at net.bytebuddy.matcher.SignatureTokenMatcher.matches(SignatureTokenMatcher.java:30)
	at net.bytebuddy.matcher.SignatureTokenMatcher.matches(SignatureTokenMatcher.java:11)
	at net.bytebuddy.matcher.ElementMatcher$Junction$Conjunction.matches(ElementMatcher.java:101)
	at net.bytebuddy.matcher.FilterableList$AbstractBase.filter(FilterableList.java:96)
	at net.bytebuddy.dynamic.scaffold.subclass.SubclassImplementationTarget.invokeConstructor(SubclassImplementationTarget.java:59)
	at net.bytebuddy.dynamic.scaffold.subclass.SubclassImplementationTarget.invokeSuper(SubclassImplementationTarget.java:45)
	at net.bytebuddy.implementation.Implementation$Target$AbstractBase.invokeDominant(Implementation.java:364)
	at net.bytebuddy.implementation.SuperMethodCall$Appender.apply(SuperMethodCall.java:95)
	at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyCode(TypeWriter.java:616)
	at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:605)
	at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:523)
	at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:4118)
	at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1628)
	at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:174)
	at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:155)
	at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2560)
	at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2662)
	at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
	at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
	at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
	at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
	... 38 more
Process finished with exit code 255

I am doing this code (an simple class written in kotlin):

package com.example.myapplication

import java.util.*
import kotlin.reflect.KProperty

open class Samples {

    private val samplesMap = mutableMapOf<String, Sample<Any>>()

    @Suppress("UNCHECKED_CAST")
    open val samples: List<Sample<Any>>
        get() = Collections.unmodifiableList(samplesMap.values.toList())

    open operator fun get(key: String): Sample<Any>? = samplesMap[key]

    open val keySample: Sample<String> by createSample(key = "key", defaultValue = "value")

    private fun <T> createSample(
            key: String,
            defaultValue: T): SampleDelegate<T> {
        val sample = ReleaseSample(key, defaultValue)
        registerSample(sample as Sample<Any>)
        return SampleDelegate(key)
    }

    private inner class SampleDelegate<out T>(val key: String) {

        operator fun getValue(samples: Samples, property: KProperty<*>): Sample<T> {
            return samplesMap[key] as Sample<T>
        }

    }

    protected fun decorate(decorator: (sample: Sample<Any>) -> Sample<Any>) {
        samplesMap.forEach { entry ->
            val key = entry.key
            val value = entry.value
            samplesMap.put(key, decorator(value))
        }
    }

    private fun registerSample(sample: Sample<Any>) {
        samplesMap[sample.key] = sample
    }

}

class ReleaseSample<out T>(
        override val key: String,
        override val value: T
) : Sample<T>

interface Sample<out T> {
    val key: String
    val value: T
}

And this code in the test section getting me into error: Mockito.spy(Samples())

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:14
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
TWiStErRobcommented, Jul 18, 2017

@warabei14 Kotlin 1.1.3 has a fix, they weren’t slow after all…

1reaction
raphwcommented, Apr 10, 2017

That’s weird, I will look into it once I find the time!

In the mean time: Could you try to access the Samples class generic properties using the Java reflection API and see if you can raise an error?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to verify when spying on kotlin class #1851 - GitHub
I have a test class with 2 tests (written in java). The tests are trying to verify the behaviour of the subject (written...
Read more >
Mockito Stubbed Spy sometimes calls and ... - Stack Overflow
Call a real method from a Kotlin class under test and; stub the inner calls it does to other methods within such class...
Read more >
Mockito - Using Spies - Baeldung
In this tutorial, we'll illustrate how to make the most out of spies in Mockito. We'll talk about the @Spy annotation and how...
Read more >
Mockito cannot mock because : final class in Kotlin - MindOrks
In this blog, we will talk about how we can mock the final class using Mockito. By default, we can't mock the final...
Read more >
Mockito Spying or Mocking Abstract Classes - Javatpoint
Abstract classes are referred to as the class declared with the abstract keyword that may or may not include the abstract methods. In...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found