How to use createInstance method of org.mockito.kotlin.internal.CreateInstance class

Best Mockito-kotlin code snippet using org.mockito.kotlin.internal.CreateInstance.createInstance

DependencyState.kt

Source:DependencyState.kt Github

copy

Full Screen

...71 }72 }73 private fun provideInstance(): T {74 val instance = when (mode) {75 DependencyMode.REAL, DependencyMode.AUTO_PROVIDED -> createInstance()76 DependencyMode.MOCK -> createMock()77 DependencyMode.SPY -> Mockito.spy(createInstance())78 DependencyMode.PROVIDED -> createProvidedInstance()79 }80 this.instanceField = instance81 return instance82 }83 private fun createMock(): T =84 mockProvider?.let { it(dependencyProviderScope) } ?: createDefaultMock()85 private fun createDefaultMock(): T = Mockito.mock(configuration.clazz.java)86 private fun createInstance(): T {87 return realProvider?.let {88 createInstanceBy(it)89 } ?: createInstanceAutomatically()90 }91 private fun createInstanceAutomatically(): T {92 return try {93 val constructor = getConstructor()94 val constructorArguments = getConstructorArguments(constructor)95 constructor.call(*constructorArguments)96 } catch (exception: Exception) {97 throw RuntimeException(98 "Couldn't automatically construct instance of dependency \"$configuration\"",99 exception100 )101 }102 }103 private fun getConstructorArguments(constructor: KFunction<T>): Array<Any> {104 return constructor.getParameterTypes()105 .map(::getSubDependencyInstanceOfType)106 .toTypedArray()107 }108 private fun KFunction<T>.getParameterTypes() =109 this.parameters.map { it.type.classifier as KClass<*> }110 private fun getConstructor(): KFunction<T> {111 val constructors = configuration.clazz.constructors112 if (configuration.clazz.isAbstract) {113 throw IllegalArgumentException(114 "Dependencies like \"${configuration.clazz.simpleName}\" which are abstract can not be " +115 "auto-provided. Please define how to instantiate it by adding a " +116 "`provide<${configuration.clazz.simpleName}> { ... }` configuration!"117 )118 }119 if (constructors.size > 1) {120 throw IllegalArgumentException(121 "Dependencies like \"${configuration.clazz.simpleName}\" which have more than one constructor " +122 "can't be auto-provided. Please define how to instantiate it by adding a " +123 "`provide<${configuration.clazz.simpleName}> { ... }` configuration!"124 )125 }126 val constructor = constructors.first()127 return constructor128 }129 private fun getSubDependencyInstanceOfType(dependencyType: KClass<*>): Any {130 return try {131 TestEnvironment.dependencies.getDependencyState(dependencyType).instance132 } catch (exception: Exception) {133 throw RuntimeException(134 "The constructor of \"${configuration.clazz.simpleName}\" needs an instance of dependency " +135 "\"${dependencyType.simpleName}\", but but it could not be retrieved.",136 exception137 )138 }139 }140 private fun createProvidedInstance(): T {141 return provider?.let {142 createInstanceBy(it)143 } ?: throw RuntimeException(144 "Cannot create provided instance, because `provider` is not set."145 )146 }147 private fun createInstanceBy(provider: DependencyProvider<T>): T {148 return try {149 provider(dependencyProviderScope)150 } catch (dependencyException: DependencyInstanceInitializationException) {151 throw dependencyException152 } catch (mockitoException: MockitoException) {153 throw mockitoException154 } catch (throwable: Throwable) {155 throw DependencyInstanceInitializationException("Provider for \"$configuration\" failed", throwable)156 }157 }158 class DependencyInstanceInitializationException(message: String, cause: Throwable) :159 Exception(message, cause)160}...

Full Screen

Full Screen

Matchers.kt

Source:Matchers.kt Github

copy

Full Screen

...22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN23 * THE SOFTWARE.24 */25package org.mockito.kotlin26import org.mockito.kotlin.internal.createInstance27import org.mockito.ArgumentMatcher28import org.mockito.ArgumentMatchers29/** Object argument that is equal to the given value. */30fun <T> eq(value: T): T {31 return ArgumentMatchers.eq(value) ?: value32}33/** Object argument that is the same as the given value. */34fun <T> same(value: T): T {35 return ArgumentMatchers.same(value) ?: value36}37/** Matches any object, excluding nulls. */38inline fun <reified T : Any> any(): T {39 return ArgumentMatchers.any(T::class.java) ?: createInstance()40}41/** Matches anything, including nulls. */42inline fun <reified T : Any> anyOrNull(): T {43 return ArgumentMatchers.any<T>() ?: createInstance()44}45/** Matches any vararg object, including nulls. */46inline fun <reified T : Any> anyVararg(): T {47 return ArgumentMatchers.any<T>() ?: createInstance()48}49/** Matches any array of type T. */50inline fun <reified T : Any?> anyArray(): Array<T> {51 return ArgumentMatchers.any(Array<T>::class.java) ?: arrayOf()52}53/**54 * Creates a custom argument matcher.55 * `null` values will never evaluate to `true`.56 *57 * @param predicate An extension function on [T] that returns `true` when a [T] matches the predicate.58 */59inline fun <reified T : Any> argThat(noinline predicate: T.() -> Boolean): T {60 return ArgumentMatchers.argThat { arg: T? -> arg?.predicate() ?: false } ?: createInstance(61 T::class62 )63}64/**65 * Registers a custom ArgumentMatcher. The original Mockito function registers the matcher and returns null,66 * here the required type is returned.67 *68 * @param matcher The ArgumentMatcher on [T] to be registered.69 */70inline fun <reified T : Any> argThat(matcher: ArgumentMatcher<T>): T {71 return ArgumentMatchers.argThat(matcher) ?: createInstance()72}73/**74 * Alias for [argThat].75 *76 * Creates a custom argument matcher.77 * `null` values will never evaluate to `true`.78 *79 * @param predicate An extension function on [T] that returns `true` when a [T] matches the predicate.80 */81inline fun <reified T : Any> argForWhich(noinline predicate: T.() -> Boolean): T {82 return argThat(predicate)83}84/**85 * Creates a custom argument matcher.86 * `null` values will never evaluate to `true`.87 *88 * @param predicate A function that returns `true` when given [T] matches the predicate.89 */90inline fun <reified T : Any> argWhere(noinline predicate: (T) -> Boolean): T {91 return argThat(predicate)92}93/**94 * Argument that implements the given class.95 */96inline fun <reified T : Any> isA(): T {97 return ArgumentMatchers.isA(T::class.java) ?: createInstance()98}99/**100 * `null` argument.101 */102fun <T : Any> isNull(): T? = ArgumentMatchers.isNull()103/**104 * Not `null` argument.105 */106fun <T : Any> isNotNull(): T? {107 return ArgumentMatchers.isNotNull()108}109/**110 * Not `null` argument.111 */112fun <T : Any> notNull(): T? {113 return ArgumentMatchers.notNull()114}115/**116 * Object argument that is reflection-equal to the given value with support for excluding117 * selected fields from a class.118 */119inline fun <reified T : Any> refEq(value: T, vararg excludeFields: String): T {120 return ArgumentMatchers.refEq<T>(value, *excludeFields) ?: createInstance()121}...

Full Screen

Full Screen

KStubbing.kt

Source:KStubbing.kt Github

copy

Full Screen

...22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN23 * THE SOFTWARE.24 */25package org.mockito.kotlin26import org.mockito.kotlin.internal.createInstance27import kotlinx.coroutines.runBlocking28import org.mockito.Mockito29import org.mockito.stubbing.OngoingStubbing30import kotlin.reflect.KClass31inline fun <T> stubbing(32 mock: T,33 stubbing: KStubbing<T>.(T) -> Unit34) {35 KStubbing(mock).stubbing(mock)36}37inline fun <T : Any> T.stub(stubbing: KStubbing<T>.(T) -> Unit): T {38 return apply { KStubbing(this).stubbing(this) }39}40class KStubbing<out T>(val mock: T) {41 fun <R> on(methodCall: R): OngoingStubbing<R> = Mockito.`when`(methodCall)42 fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R> {43 val r = try {44 mock.methodCall()45 } catch (e: NullPointerException) {46 // An NPE may be thrown by the Kotlin type system when the MockMethodInterceptor returns a47 // null value for a non-nullable generic type.48 // We catch this NPE to return a valid instance.49 // The Mockito state has already been modified at this point to reflect50 // the wanted changes.51 createInstance(c)52 }53 return Mockito.`when`(r)54 }55 inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R> {56 return onGeneric(methodCall, R::class)57 }58 fun <R> on(methodCall: T.() -> R): OngoingStubbing<R> {59 return try {60 Mockito.`when`(mock.methodCall())61 } catch (e: NullPointerException) {62 throw MockitoKotlinException(63 "NullPointerException thrown when stubbing.\nThis may be due to two reasons:\n\t- The method you're trying to stub threw an NPE: look at the stack trace below;\n\t- You're trying to stub a generic method: try `onGeneric` instead.",64 e65 )...

Full Screen

Full Screen

CreateInstance.kt

Source:CreateInstance.kt Github

copy

Full Screen

...24 */25package org.mockito.kotlin.internal26import kotlin.reflect.KClass27import java.lang.reflect.Array as JavaArray28inline fun <reified T : Any> createInstance(): T {29 return when (T::class) {30 Boolean::class -> false as T31 Byte::class -> 0.toByte() as T32 Char::class -> 0.toChar() as T33 Short::class -> 0.toShort() as T34 Int::class -> 0 as T35 Long::class -> 0L as T36 Float::class -> 0f as T37 Double::class -> 0.0 as T38 else -> createInstance(T::class)39 }40}41fun <T : Any> createInstance(kClass: KClass<T>): T {42 return castNull()43}44/**45 * Uses a quirk in the bytecode generated by Kotlin46 * to cast [null] to a non-null type.47 *48 * See https://youtrack.jetbrains.com/issue/KT-8135.49 */50@Suppress("UNCHECKED_CAST")51private fun <T> castNull(): T = null as T...

Full Screen

Full Screen

Mockito.kt

Source:Mockito.kt Github

copy

Full Screen

1package com.tschuchort.compiletesting2import com.nhaarman.mockitokotlin2.internal.createInstance3import org.mockito.AdditionalMatchers4class MockitoAdditionalMatchersKotlin {5 companion object {6 inline fun <reified T : Any> not(matcher: T): T {7 return AdditionalMatchers.not(matcher) ?: createInstance()8 }9 inline fun <reified T : Any> or(left: T, right: T): T {10 return AdditionalMatchers.or(left, right) ?: createInstance()11 }12 inline fun <reified T : Any> and(left: T, right: T): T {13 return AdditionalMatchers.and(left, right) ?: createInstance()14 }15 inline fun <reified T : Comparable<T>> geq(value: T): T {16 return AdditionalMatchers.geq(value) ?: createInstance()17 }18 inline fun <reified T : Comparable<T>> leq(value: T): T {19 return AdditionalMatchers.leq(value) ?: createInstance()20 }21 inline fun <reified T : Comparable<T>> gt(value: T): T {22 return AdditionalMatchers.gt(value) ?: createInstance()23 }24 inline fun <reified T : Comparable<T>> lt(value: T): T {25 return AdditionalMatchers.lt(value) ?: createInstance()26 }27 inline fun <reified T : Comparable<T>> cmpEq(value: T): T {28 return AdditionalMatchers.cmpEq(value) ?: createInstance()29 }30 fun find(regex: Regex): String {31 return AdditionalMatchers.find(regex.pattern) ?: createInstance()32 }33 fun eq(value: Float, delta: Float): Float {34 return AdditionalMatchers.eq(value, delta)35 }36 fun eq(value: Double, delta: Double): Double {37 return AdditionalMatchers.eq(value, delta)38 }39 }40}...

Full Screen

Full Screen

TestUtils.kt

Source:TestUtils.kt Github

copy

Full Screen

1package eywa.projectcodex2import eywa.projectcodex.components.archerRoundScore.scorePad.infoTable.ScorePadData3import org.mockito.ArgumentCaptor4import org.mockito.Mockito5class TestUtils {6 companion object {7 private val defaultColumnHeaderOrder = listOf(8 ScorePadData.ColumnHeader.END_STRING,9 ScorePadData.ColumnHeader.HITS,10 ScorePadData.ColumnHeader.SCORE,11 ScorePadData.ColumnHeader.GOLDS,12 ScorePadData.ColumnHeader.RUNNING_TOTAL13 )14 /**15 * Use this when the usual argumentCaptor.capture() apparently throws a null16 *17 * Source:18 * - https://stackoverflow.com/a/4606420419 * - https://github.com/android/architecture-components-samples/blob/master/BasicRxJavaSampleKotlin/app/src/test/java/com/example/android/observability/MockitoKotlinHelpers.kt20 *21 * @return ArgumentCaptor.capture() as nullable type to avoid java.lang.IllegalStateException when null is22 * returned23 */24 fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()25 /**26 * Source: https://github.com/mockito/mockito-kotlin/blob/main/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/internal/CreateInstance.kt27 * TODO Use kotlin mockito library ^^28 */29 fun <T> anyMatcher(): T = Mockito.any() ?: castNull()30 @Suppress("UNCHECKED_CAST")31 private fun <T> castNull(): T = null as T32 }33}...

Full Screen

Full Screen

ParametersTransformerTest.kt

Source:ParametersTransformerTest.kt Github

copy

Full Screen

...4import org.mockito.kotlin.doReturn5import org.mockito.kotlin.mock6import org.mockito.kotlin.whenever7import kotlin.reflect.KParameter8import kotlin.reflect.full.createInstance9internal class ParametersTransformerTest {10 @Test11 fun `create WithNoAnnotations returnsBodyTransformer`() {12 val param = mock<KParameter>().also {13 doReturn(emptyList<Annotation>()).whenever(it).annotations14 }15 assert(ParametersTransformerFactory.create(param) is BodyParametersTransformer)16 }17 @Test18 fun `create WithMultipleAnnotations withoutBodyAnnotation returnsBodyTransformer`() {19 val param = mock<KParameter>().also {20 doReturn(listOf(CordaSerializable::class.createInstance())).whenever(it).annotations21 }22 assert(ParametersTransformerFactory.create(param) is BodyParametersTransformer)23 }24}...

Full Screen

Full Screen

NullCasterTest.kt

Source:NullCasterTest.kt Github

copy

Full Screen

1package test.createinstance2import com.nhaarman.expect.expect3import org.mockito.kotlin.internal.createInstance4import org.junit.Test5import test.TestBase6class NullCasterTest : TestBase() {7 @Test8 fun createInstance() {9 /* When */10 val result = createInstance(String::class)11 /* Then */12 expect(result).toBeNull()13 }14 @Test15 fun kotlinAcceptsNullValue() {16 /* Given */17 val s: String = createInstance(String::class)18 /* When */19 acceptNonNullableString(s)20 }21 private fun acceptNonNullableString(@Suppress("UNUSED_PARAMETER") s: String) {22 }23}...

Full Screen

Full Screen

createInstance

Using AI Code Generation

copy

Full Screen

1val mock = createInstance<Mock> ( )2val mock = createInstance ( )3val mock = createInstance<Mock> ( )4val mock = createInstance ( )5val mock = createInstance<Mock> ( )6val mock = createInstance ( )7val mock = createInstance<Mock> ( )8val mock = createInstance ( )9val mock = createInstance<Mock> ( )10val mock = createInstance ( )11val mock = createInstance<Mock> ( )12val mock = createInstance ( )13val mock = createInstance<Mock> ( )14val mock = createInstance ( )15val mock = createInstance<Mock> ( )16val mock = createInstance ( )17val mock = createInstance<Mock> ( )18val mock = createInstance ( )19val mock = createInstance<Mock> ( )20val mock = createInstance ( )21val mock = createInstance<Mock> ( )

Full Screen

Full Screen

createInstance

Using AI Code Generation

copy

Full Screen

1val mock = createInstance<Mock>()2val mock = createInstance<Mock>(constructorArgs = arrayOf("arg1", 2))3val mock = createInstance<Mock>(constructorArgs = arrayOf("arg1", 2), name = "customName")4val mock = createInstance<Mock>(name = "customName")5val mock = createInstance<Mock>(constructorArgs = arrayOf("arg1", 2), name = "customName")6val mock = createInstance<Mock>(name = "customName")7val mock = createInstance<Mock>(constructorArgs = arrayOf("arg1", 2), name = "customName")8val mock = createInstance<Mock>(name = "customName")9val mock = createInstance<Mock>(constructorArgs = arrayOf("arg1", 2), name = "customName")10val mock = createInstance<Mock>(name = "customName")11val mock = createInstance<Mock>(constructorArgs = arrayOf("arg1", 2), name = "customName")12val mock = createInstance<Mock>(name = "customName")13val mock = createInstance<Mock>(constructorArgs = arrayOf("arg1", 2), name = "customName")

Full Screen

Full Screen

createInstance

Using AI Code Generation

copy

Full Screen

1 val mock = createInstance<MockedClass>()2 whenever(mock.foo()).thenReturn("bar")3 assertEquals("bar", mock.foo())4 verify(mock).foo()5}6fun `test createInstance with parameters`() {7 val mock = createInstance(MockedClass::class, "foo", 1)8 whenever(mock.foo()).thenReturn("bar")9 assertEquals("bar", mock.foo())10 verify(mock).foo()11}12fun `test createInstance with companion object`() {13 val mock = createInstance(MockedClass::class, Companion)14 whenever(mock.foo()).thenReturn("bar")15 assertEquals("bar", mock.foo())16 verify(mock).foo()17}18fun `test createInstance with companion object and parameters`() {19 val mock = createInstance(MockedClass::class, Companion, "foo", 1

Full Screen

Full Screen

createInstance

Using AI Code Generation

copy

Full Screen

1val mock = createInstance<MockedClass>()2verify(mock).method()3whenever(mock.method()).thenReturn("some value")4doReturn("some value").whenever(mock).method()5doThrow(RuntimeException("some error")).whenever(mock).method()6doAnswer { "some value" }.whenever(mock).method()7doAnswer { throw RuntimeException("some error") }.whenever(mock).method()8doAnswer { mock.method() }.whenever(mock).method()9val mock = createInstance<MockedClass>()10verify(mock).method()11whenever(mock.method()).thenReturn("some value")12doReturn("some value").whenever(mock).method()13doThrow(RuntimeException("some error")).whenever(mock).method()14doAnswer { "some value" }.whenever(mock).method()15doAnswer { throw RuntimeException("some error") }.whenever(mock).method()16doAnswer { mock.method() }.whenever(mock).method()17val mock = createInstance<MockedClass>()18verify(mock).method()19whenever(mock.method()).thenReturn("some value")20doReturn("some value").whenever(mock).method()21doThrow(RuntimeException

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito-kotlin automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in CreateInstance

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful