How to use mock method of org.mockito.kotlin.UseConstructor class

Best Mockito-kotlin code snippet using org.mockito.kotlin.UseConstructor.mock

Mocking.kt

Source:Mocking.kt Github

copy

Full Screen

...21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,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.Incubating27import org.mockito.MockSettings28import org.mockito.Mockito29import org.mockito.listeners.InvocationListener30import org.mockito.mock.SerializableMode31import org.mockito.stubbing.Answer32import kotlin.DeprecationLevel.ERROR33import kotlin.reflect.KClass34/**35 * Creates a mock for [T].36 *37 * @param extraInterfaces Specifies extra interfaces the mock should implement.38 * @param name Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.39 * @param spiedInstance Specifies the instance to spy on. Makes sense only for spies/partial mocks.40 * @param defaultAnswer Specifies default answers to interactions.41 * @param serializable Configures the mock to be serializable.42 * @param serializableMode Configures the mock to be serializable with a specific serializable mode.43 * @param verboseLogging Enables real-time logging of method invocations on this mock.44 * @param invocationListeners Registers a listener for method invocations on this mock. The listener is notified every time a method on this mock is called.45 * @param stubOnly A stub-only mock does not record method invocations, thus saving memory but disallowing verification of invocations.46 * @param useConstructor Mockito attempts to use constructor when creating instance of the mock.47 * @param outerInstance Makes it possible to mock non-static inner classes in conjunction with [useConstructor].48 * @param lenient Lenient mocks bypass "strict stubbing" validation.49 */50inline fun <reified T : Any> mock(51 extraInterfaces: Array<out KClass<out Any>>? = null,52 name: String? = null,53 spiedInstance: Any? = null,54 defaultAnswer: Answer<Any>? = null,55 serializable: Boolean = false,56 serializableMode: SerializableMode? = null,57 verboseLogging: Boolean = false,58 invocationListeners: Array<InvocationListener>? = null,59 stubOnly: Boolean = false,60 @Incubating useConstructor: UseConstructor? = null,61 @Incubating outerInstance: Any? = null,62 @Incubating lenient: Boolean = false63): T {64 return Mockito.mock(65 T::class.java,66 withSettings(67 extraInterfaces = extraInterfaces,68 name = name,69 spiedInstance = spiedInstance,70 defaultAnswer = defaultAnswer,71 serializable = serializable,72 serializableMode = serializableMode,73 verboseLogging = verboseLogging,74 invocationListeners = invocationListeners,75 stubOnly = stubOnly,76 useConstructor = useConstructor,77 outerInstance = outerInstance,78 lenient = lenient79 )80 )!!81}82/**83 * Creates a mock for [T], allowing for immediate stubbing.84 *85 * @param extraInterfaces Specifies extra interfaces the mock should implement.86 * @param name Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.87 * @param spiedInstance Specifies the instance to spy on. Makes sense only for spies/partial mocks.88 * @param defaultAnswer Specifies default answers to interactions.89 * @param serializable Configures the mock to be serializable.90 * @param serializableMode Configures the mock to be serializable with a specific serializable mode.91 * @param verboseLogging Enables real-time logging of method invocations on this mock.92 * @param invocationListeners Registers a listener for method invocations on this mock. The listener is notified every time a method on this mock is called.93 * @param stubOnly A stub-only mock does not record method invocations, thus saving memory but disallowing verification of invocations.94 * @param useConstructor Mockito attempts to use constructor when creating instance of the mock.95 * @param outerInstance Makes it possible to mock non-static inner classes in conjunction with [useConstructor].96 * @param lenient Lenient mocks bypass "strict stubbing" validation.97 */98inline fun <reified T : Any> mock(99 extraInterfaces: Array<out KClass<out Any>>? = null,100 name: String? = null,101 spiedInstance: Any? = null,102 defaultAnswer: Answer<Any>? = null,103 serializable: Boolean = false,104 serializableMode: SerializableMode? = null,105 verboseLogging: Boolean = false,106 invocationListeners: Array<InvocationListener>? = null,107 stubOnly: Boolean = false,108 @Incubating useConstructor: UseConstructor? = null,109 @Incubating outerInstance: Any? = null,110 @Incubating lenient: Boolean = false,111 stubbing: KStubbing<T>.(T) -> Unit112): T {113 return Mockito.mock(114 T::class.java,115 withSettings(116 extraInterfaces = extraInterfaces,117 name = name,118 spiedInstance = spiedInstance,119 defaultAnswer = defaultAnswer,120 serializable = serializable,121 serializableMode = serializableMode,122 verboseLogging = verboseLogging,123 invocationListeners = invocationListeners,124 stubOnly = stubOnly,125 useConstructor = useConstructor,126 outerInstance = outerInstance,127 lenient = lenient128 )129 ).apply { KStubbing(this).stubbing(this) }!!130}131/**132 * Allows mock creation with additional mock settings.133 * See [MockSettings].134 *135 * @param extraInterfaces Specifies extra interfaces the mock should implement.136 * @param name Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.137 * @param spiedInstance Specifies the instance to spy on. Makes sense only for spies/partial mocks.138 * @param defaultAnswer Specifies default answers to interactions.139 * @param serializable Configures the mock to be serializable.140 * @param serializableMode Configures the mock to be serializable with a specific serializable mode.141 * @param verboseLogging Enables real-time logging of method invocations on this mock.142 * @param invocationListeners Registers a listener for method invocations on this mock. The listener is notified every time a method on this mock is called.143 * @param stubOnly A stub-only mock does not record method invocations, thus saving memory but disallowing verification of invocations.144 * @param useConstructor Mockito attempts to use constructor when creating instance of the mock.145 * @param outerInstance Makes it possible to mock non-static inner classes in conjunction with [useConstructor].146 * @param lenient Lenient mocks bypass "strict stubbing" validation.147 */148fun withSettings(149 extraInterfaces: Array<out KClass<out Any>>? = null,150 name: String? = null,151 spiedInstance: Any? = null,152 defaultAnswer: Answer<Any>? = null,153 serializable: Boolean = false,154 serializableMode: SerializableMode? = null,155 verboseLogging: Boolean = false,156 invocationListeners: Array<InvocationListener>? = null,157 stubOnly: Boolean = false,158 @Incubating useConstructor: UseConstructor? = null,159 @Incubating outerInstance: Any? = null,160 @Incubating lenient: Boolean = false161): MockSettings = Mockito.withSettings().apply {162 extraInterfaces?.let { extraInterfaces(*it.map { it.java }.toTypedArray()) }163 name?.let { name(it) }164 spiedInstance?.let { spiedInstance(it) }165 defaultAnswer?.let { defaultAnswer(it) }166 if (serializable) serializable()167 serializableMode?.let { serializable(it) }168 if (verboseLogging) verboseLogging()169 invocationListeners?.let { invocationListeners(*it) }170 if (stubOnly) stubOnly()171 useConstructor?.let { useConstructor(*it.args) }172 outerInstance?.let { outerInstance(it) }173 if (lenient) lenient()174}175class UseConstructor private constructor(val args: Array<Any>) {176 companion object {177 /** Invokes the parameterless constructor. */178 fun parameterless() = UseConstructor(emptyArray())179 /** Invokes a constructor with given arguments. */180 fun withArguments(vararg arguments: Any): UseConstructor {181 return UseConstructor(arguments.asList().toTypedArray())182 }183 }184}185@Deprecated(186 "Use mock() with optional arguments instead.",187 ReplaceWith("mock<T>(defaultAnswer = a)"),188 level = ERROR189)190inline fun <reified T : Any> mock(a: Answer<Any>): T = mock(defaultAnswer = a)191@Deprecated(192 "Use mock() with optional arguments instead.",193 ReplaceWith("mock<T>(name = s)"),194 level = ERROR195)196inline fun <reified T : Any> mock(s: String): T = mock(name = s)197@Suppress("DeprecatedCallableAddReplaceWith")198@Deprecated("Use mock() with optional arguments instead.", level = ERROR)199inline fun <reified T : Any> mock(s: MockSettings): T = Mockito.mock(T::class.java, s)!!...

Full Screen

Full Screen

MockingTest.kt

Source:MockingTest.kt Github

copy

Full Screen

1package test2import com.nhaarman.expect.expect3import com.nhaarman.expect.expectErrorWithMessage4import com.nhaarman.expect.fail5import org.mockito.kotlin.UseConstructor.Companion.parameterless6import org.mockito.kotlin.UseConstructor.Companion.withArguments7import org.mockito.kotlin.doReturn8import org.mockito.kotlin.mock9import org.mockito.kotlin.verify10import org.mockito.kotlin.whenever11import org.junit.Test12import org.mockito.Mockito13import org.mockito.exceptions.verification.WantedButNotInvoked14import org.mockito.invocation.DescribedInvocation15import org.mockito.kotlin.argumentCaptor16import org.mockito.listeners.InvocationListener17import org.mockito.mock.SerializableMode.BASIC18import java.io.PrintStream19import java.io.Serializable20import java.util.*21class MockingTest : TestBase() {22 private lateinit var propertyInterfaceVariable: MyInterface23 private lateinit var propertyClassVariable: MyClass24 @Test25 fun localInterfaceValue() {26 /* When */27 val instance: MyInterface = mock()28 /* Then */29 expect(instance).toNotBeNull()30 }31 @Test32 fun propertyInterfaceVariable() {33 /* When */34 propertyInterfaceVariable = mock()35 /* Then */36 expect(propertyInterfaceVariable).toNotBeNull()37 }38 @Test39 fun localClassValue() {40 /* When */41 val instance: MyClass = mock()42 /* Then */43 expect(instance).toNotBeNull()44 }45 @Test46 fun propertyClassVariable() {47 /* When */48 propertyClassVariable = mock()49 /* Then */50 expect(propertyClassVariable).toNotBeNull()51 }52 @Test53 fun untypedVariable() {54 /* When */55 val instance = mock<MyClass>()56 expect(instance).toNotBeNull()57 }58 @Test59 fun deepStubs() {60 val cal: Calendar = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)61 whenever(cal.time.time).thenReturn(123L)62 expect(cal.time.time).toBe(123L)63 }64 @Test65 fun testMockStubbing_lambda() {66 /* Given */67 val mock = mock<Open>() {68 on { stringResult() } doReturn "A"69 }70 /* When */71 val result = mock.stringResult()72 /* Then */73 expect(result).toBe("A")74 }75 @Test76 fun testMockStubbing_normalOverridesLambda() {77 /* Given */78 val mock = mock<Open>() {79 on { stringResult() }.doReturn("A")80 }81 whenever(mock.stringResult()).thenReturn("B")82 /* When */83 val result = mock.stringResult()84 /* Then */85 expect(result).toBe("B")86 }87 @Test88 fun mock_withCustomDefaultAnswer_parameterName() {89 /* Given */90 val mock = mock<Methods>(defaultAnswer = Mockito.RETURNS_SELF)91 /* When */92 val result = mock.builderMethod()93 /* Then */94 expect(result).toBe(mock)95 }96 @Test97 fun mock_withSettingsAPI_extraInterfaces() {98 /* Given */99 val mock = mock<Methods>(100 extraInterfaces = arrayOf(ExtraInterface::class)101 )102 /* Then */103 expect(mock).toBeInstanceOf<ExtraInterface>()104 }105 @Test106 fun mock_withSettingsAPI_name() {107 /* Given */108 val mock = mock<Methods>(name = "myName")109 /* When */110 expectErrorWithMessage("myName.stringResult()") on {111 verify(mock).stringResult()112 }113 }114 @Test115 fun mock_withSettingsAPI_defaultAnswer() {116 /* Given */117 val mock = mock<Methods>(defaultAnswer = Mockito.RETURNS_MOCKS)118 /* When */119 val result = mock.nonDefaultReturnType()120 /* Then */121 expect(result).toNotBeNull()122 }123 @Test124 fun mock_withSettingsAPI_serializable() {125 /* Given */126 val mock = mock<Methods>(serializable = true)127 /* Then */128 expect(mock).toBeInstanceOf<Serializable>()129 }130 @Test131 fun mock_withSettingsAPI_serializableMode() {132 /* Given */133 val mock = mock<Methods>(serializableMode = BASIC)134 /* Then */135 expect(mock).toBeInstanceOf<Serializable>()136 }137 @Test138 fun mock_withSettingsAPI_verboseLogging() {139 /* Given */140 val out = mock<PrintStream>()141 System.setOut(out)142 val mock = mock<Methods>(verboseLogging = true)143 try {144 /* When */145 verify(mock).stringResult()146 fail("Expected an exception")147 } catch (e: WantedButNotInvoked) {148 /* Then */149 argumentCaptor<DescribedInvocation>().apply {150 verify(out).println(capture())151 expect(lastValue.toString()).toBe("methods.stringResult();")152 }153 }154 }155 @Test156 fun mock_withSettingsAPI_invocationListeners() {157 /* Given */158 var bool = false159 val mock = mock<Methods>(invocationListeners = arrayOf(InvocationListener { bool = true }))160 /* When */161 mock.stringResult()162 /* Then */163 expect(bool).toHold()164 }165 @Test166 fun mock_withSettingsAPI_stubOnly() {167 /* Given */168 val mock = mock<Methods>(stubOnly = true)169 /* Expect */170 expectErrorWithMessage("is a stubOnly() mock") on {171 /* When */172 verify(mock).stringResult()173 }174 }175 @Test176 fun mock_withSettingsAPI_useConstructor() {177 /* Given */178 expectErrorWithMessage("Unable to create mock instance of type ") on {179 mock<ThrowingConstructor>(useConstructor = parameterless()) {}180 }181 }182 @Test183 fun mock_withSettingsAPI_useConstructorWithArguments_failing() {184 /* Given */185 expectErrorWithMessage("Unable to create mock instance of type ") on {186 mock<ThrowingConstructorWithArgument>(useConstructor = withArguments("Test")) {}187 }188 }189 @Test190 fun mock_withSettingsAPI_useConstructorWithArguments() {191 /* When */192 val result = mock<NonThrowingConstructorWithArgument>(useConstructor = withArguments("Test")) {}193 /* Then */194 expect(result).toNotBeNull()195 }196 @Test197 fun mockStubbing_withSettingsAPI_extraInterfaces() {198 /* Given */199 val mock = mock<Methods>(extraInterfaces = arrayOf(ExtraInterface::class)) {}200 /* Then */201 expect(mock).toBeInstanceOf<ExtraInterface>()202 }203 @Test204 fun mockStubbing_withSettingsAPI_name() {205 /* Given */206 val mock = mock<Methods>(name = "myName") {}207 /* When */208 expectErrorWithMessage("myName.stringResult()") on {209 verify(mock).stringResult()210 }211 }212 @Test213 fun mockStubbing_withSettingsAPIAndStubbing_name() {214 /* Given */215 val mock = mock<Methods>(name = "myName") {216 on { nullableStringResult() } doReturn "foo"217 }218 /* When */219 val result = mock.nullableStringResult()220 /* Then */221 expect(result).toBe("foo")222 }223 @Test224 fun mockStubbing_withSettingsAPI_defaultAnswer() {225 /* Given */226 val mock = mock<Methods>(defaultAnswer = Mockito.RETURNS_MOCKS) {}227 /* When */228 val result = mock.nonDefaultReturnType()229 /* Then */230 expect(result).toNotBeNull()231 }232 @Test233 fun mockStubbing_withSettingsAPI_serializable() {234 /* Given */235 val mock = mock<Methods>(serializable = true) {}236 /* Then */237 expect(mock).toBeInstanceOf<Serializable>()238 }239 @Test240 fun mockStubbing_withSettingsAPI_serializableMode() {241 /* Given */242 val mock = mock<Methods>(serializableMode = BASIC) {}243 /* Then */244 expect(mock).toBeInstanceOf<Serializable>()245 }246 @Test247 fun mockStubbing_withSettingsAPI_verboseLogging() {248 /* Given */249 val out = mock<PrintStream>()250 System.setOut(out)251 val mock = mock<Methods>(verboseLogging = true) {}252 try {253 /* When */254 verify(mock).stringResult()255 fail("Expected an exception")256 } catch (e: WantedButNotInvoked) {257 /* Then */258 argumentCaptor<DescribedInvocation>().apply {259 verify(out).println(capture())260 expect(lastValue.toString()).toBe("methods.stringResult();")261 }262 }263 }264 @Test265 fun mockStubbing_withSettingsAPI_invocationListeners() {266 /* Given */267 var bool = false268 val mock = mock<Methods>(invocationListeners = arrayOf(InvocationListener { bool = true })) {}269 /* When */270 mock.stringResult()271 /* Then */272 expect(bool).toHold()273 }274 @Test275 fun mockStubbing_withSettingsAPI_stubOnly() {276 /* Given */277 val mock = mock<Methods>(stubOnly = true) {}278 /* Expect */279 expectErrorWithMessage("is a stubOnly() mock") on {280 /* When */281 verify(mock).stringResult()282 }283 }284 @Test285 fun mockStubbing_withSettingsAPI_useConstructor() {286 /* Given */287 expectErrorWithMessage("Unable to create mock instance of type ") on {288 mock<ThrowingConstructor>(useConstructor = parameterless()) {}289 }290 }291 private interface MyInterface292 private open class MyClass293}...

Full Screen

Full Screen

MockitoPlugins.kt

Source:MockitoPlugins.kt Github

copy

Full Screen

1package com.episode6.mockspresso2.plugins.mockito2import com.episode6.mockspresso2.MockspressoBuilder3import com.episode6.mockspresso2.MockspressoProperties4import com.episode6.mockspresso2.api.FallbackObjectMaker5import com.episode6.mockspresso2.dependency6import com.episode6.mockspresso2.reflect.DependencyKey7import com.episode6.mockspresso2.reflect.asJClass8import com.episode6.mockspresso2.reflect.dependencyKey9import com.episode6.mockspresso2.reflect.typeToken10import org.mockito.Incubating11import org.mockito.Mockito12import org.mockito.kotlin.KStubbing13import org.mockito.kotlin.UseConstructor14import org.mockito.kotlin.spy15import org.mockito.kotlin.withSettings16import org.mockito.listeners.InvocationListener17import org.mockito.mock.SerializableMode18import org.mockito.stubbing.Answer19import kotlin.reflect.KClass20/**21 * Use mockito to generate fallback objects for dependencies that are not present in the mockspresso instance22 */23fun MockspressoBuilder.fallbackWithMockito(): MockspressoBuilder =24 makeFallbackObjectsWith(object : FallbackObjectMaker {25 override fun <T> makeObject(key: DependencyKey<T>): T = Mockito.mock(key.token.asJClass())26 })27/**28 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the29 * supplied qualifier annotation. If you need a reference to the mock dependency, consider [MockspressoProperties.mock]30 * instead.31 */32inline fun <reified T : Any?> MockspressoBuilder.mock(33 qualifier: Annotation? = null,34 extraInterfaces: Array<out KClass<out Any>>? = null,35 name: String? = null,36 spiedInstance: Any? = null,37 defaultAnswer: Answer<Any>? = null,38 serializable: Boolean = false,39 serializableMode: SerializableMode? = null,40 verboseLogging: Boolean = false,41 invocationListeners: Array<InvocationListener>? = null,42 stubOnly: Boolean = false,43 @Incubating useConstructor: UseConstructor? = null,44 @Incubating outerInstance: Any? = null,45 @Incubating lenient: Boolean = false46): MockspressoBuilder = dependency(qualifier) {47 Mockito.mock(48 T::class.java,49 withSettings(50 extraInterfaces = extraInterfaces,51 name = name,52 spiedInstance = spiedInstance,53 defaultAnswer = defaultAnswer,54 serializable = serializable,55 serializableMode = serializableMode,56 verboseLogging = verboseLogging,57 invocationListeners = invocationListeners,58 stubOnly = stubOnly,59 useConstructor = useConstructor,60 outerInstance = outerInstance,61 lenient = lenient62 )63 )!!64}65/**66 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the67 * supplied qualifier annotation. If you need a reference to the mock dependency, consider [MockspressoProperties.mock]68 * instead.69 */70inline fun <reified T : Any?> MockspressoBuilder.mock(71 qualifier: Annotation? = null,72 extraInterfaces: Array<out KClass<out Any>>? = null,73 name: String? = null,74 spiedInstance: Any? = null,75 defaultAnswer: Answer<Any>? = null,76 serializable: Boolean = false,77 serializableMode: SerializableMode? = null,78 verboseLogging: Boolean = false,79 invocationListeners: Array<InvocationListener>? = null,80 stubOnly: Boolean = false,81 @Incubating useConstructor: UseConstructor? = null,82 @Incubating outerInstance: Any? = null,83 @Incubating lenient: Boolean = false,84 noinline stubbing: KStubbing<T>.(T) -> Unit85): MockspressoBuilder = dependency(qualifier) {86 Mockito.mock(87 T::class.java,88 withSettings(89 extraInterfaces = extraInterfaces,90 name = name,91 spiedInstance = spiedInstance,92 defaultAnswer = defaultAnswer,93 serializable = serializable,94 serializableMode = serializableMode,95 verboseLogging = verboseLogging,96 invocationListeners = invocationListeners,97 stubOnly = stubOnly,98 useConstructor = useConstructor,99 outerInstance = outerInstance,100 lenient = lenient101 )102 ).apply { KStubbing(this).stubbing(this) }!!103}104/**105 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the106 * supplied qualifier annotation and will be accessible via the returned lazy.107 */108inline fun <reified T : Any?> MockspressoProperties.mock(109 qualifier: Annotation? = null,110 extraInterfaces: Array<out KClass<out Any>>? = null,111 name: String? = null,112 spiedInstance: Any? = null,113 defaultAnswer: Answer<Any>? = null,114 serializable: Boolean = false,115 serializableMode: SerializableMode? = null,116 verboseLogging: Boolean = false,117 invocationListeners: Array<InvocationListener>? = null,118 stubOnly: Boolean = false,119 @Incubating useConstructor: UseConstructor? = null,120 @Incubating outerInstance: Any? = null,121 @Incubating lenient: Boolean = false122): Lazy<T> = dependency(qualifier) {123 Mockito.mock(124 T::class.java,125 withSettings(126 extraInterfaces = extraInterfaces,127 name = name,128 spiedInstance = spiedInstance,129 defaultAnswer = defaultAnswer,130 serializable = serializable,131 serializableMode = serializableMode,132 verboseLogging = verboseLogging,133 invocationListeners = invocationListeners,134 stubOnly = stubOnly,135 useConstructor = useConstructor,136 outerInstance = outerInstance,137 lenient = lenient138 )139 )!!140}141/**142 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the143 * supplied qualifier annotation and will be accessible via the returned lazy.144 */145inline fun <reified T : Any?> MockspressoProperties.mock(146 qualifier: Annotation? = null,147 extraInterfaces: Array<out KClass<out Any>>? = null,148 name: String? = null,149 spiedInstance: Any? = null,150 defaultAnswer: Answer<Any>? = null,151 serializable: Boolean = false,152 serializableMode: SerializableMode? = null,153 verboseLogging: Boolean = false,154 invocationListeners: Array<InvocationListener>? = null,155 stubOnly: Boolean = false,156 @Incubating useConstructor: UseConstructor? = null,157 @Incubating outerInstance: Any? = null,158 @Incubating lenient: Boolean = false,159 noinline stubbing: KStubbing<T>.(T) -> Unit160): Lazy<T> = dependency(qualifier) {161 Mockito.mock(162 T::class.java,163 withSettings(164 extraInterfaces = extraInterfaces,165 name = name,166 spiedInstance = spiedInstance,167 defaultAnswer = defaultAnswer,168 serializable = serializable,169 serializableMode = serializableMode,170 verboseLogging = verboseLogging,171 invocationListeners = invocationListeners,172 stubOnly = stubOnly,173 useConstructor = useConstructor,174 outerInstance = outerInstance,175 lenient = lenient176 )177 ).apply { KStubbing(this).stubbing(this) }!!178}179/**180 * Create a real object of [T] using mockspresso then wrap it in a mockito [spy]. This spy will be part of the mockspresso181 * graph and can be used by other real objects (and then verified in test code).182 */183inline fun <reified T : Any?> MockspressoProperties.spy(qualifier: Annotation? = null): Lazy<T> =184 interceptRealImplementation(dependencyKey<T>(qualifier), typeToken<T>()) { spy(it) }185/**186 * Create a real object of [T] using mockspresso then wrap it in a mockito [spy]. This spy will be part of the mockspresso187 * graph and can be used by other real objects (and then verified in test code). The [stubbing] will be applied to the188 * spy before it is injected as a dependency into other classes.189 */190inline fun <reified T : Any?> MockspressoProperties.spy(191 qualifier: Annotation? = null,192 noinline stubbing: KStubbing<T>.(T) -> Unit193): Lazy<T> = interceptRealImplementation(dependencyKey<T>(qualifier), typeToken<T>()) { spy(it, stubbing) }194/**195 * Create a real object of type [IMPL] using mockspresso then wrap it in a mockito [spy] (the object will be bound196 * using type [BIND]). This spy will be part of the mockspresso graph and can be used by other real objects197 * (and then verified in test code).198 */199inline fun <reified BIND : Any?, reified IMPL : BIND> MockspressoProperties.spyImplOf(qualifier: Annotation? = null): Lazy<IMPL> =200 interceptRealImplementation(dependencyKey<BIND>(qualifier), typeToken<IMPL>()) { spy(it) }201/**202 * Create a real object of type [IMPL] using mockspresso then wrap it in a mockito [spy] (the object will be bound203 * using type [BIND]). This spy will be part of the mockspresso graph and can be used by other real objects204 * (and then verified in test code). The [stubbing] will be applied to the spy before it is injected as a dependency205 * into other classes.206 */207inline fun <reified BIND : Any?, reified IMPL : BIND> MockspressoProperties.spyImplOf(208 qualifier: Annotation? = null,209 noinline stubbing: KStubbing<IMPL>.(IMPL) -> Unit210): Lazy<IMPL> = interceptRealImplementation(dependencyKey<BIND>(qualifier), typeToken<IMPL>()) { spy(it, stubbing) }...

Full Screen

Full Screen

AemArticleManagerTest.kt

Source:AemArticleManagerTest.kt Github

copy

Full Screen

...14import org.junit.Assert.assertEquals15import org.junit.Before16import org.junit.Test17import org.junit.runner.RunWith18import org.mockito.Mockito.CALLS_REAL_METHODS19import org.mockito.Mockito.RETURNS_DEEP_STUBS20import org.mockito.Mockito.verifyNoInteractions21import org.mockito.kotlin.UseConstructor22import org.mockito.kotlin.any23import org.mockito.kotlin.doReturn24import org.mockito.kotlin.eq25import org.mockito.kotlin.mock26import org.mockito.kotlin.never27import org.mockito.kotlin.stub28import org.mockito.kotlin.verify29import org.mockito.kotlin.verifyNoMoreInteractions30import org.mockito.kotlin.whenever31import retrofit2.Response32@RunWith(AndroidJUnit4::class)33@OptIn(ExperimentalCoroutinesApi::class)34class AemArticleManagerTest {35 private lateinit var aemDb: ArticleRoomDatabase36 private lateinit var api: AemApi37 private lateinit var fileManager: AemArticleManager.FileManager38 private lateinit var manifestManager: ManifestManager39 private val testScope = TestScope()40 private lateinit var articleManager: AemArticleManager41 @Before42 fun setup() {43 aemDb = mock(defaultAnswer = RETURNS_DEEP_STUBS) {44 onBlocking { resourceDao().getAll() } doReturn emptyList()45 }46 api = mock()47 fileManager = mock()48 manifestManager = mock()49 articleManager = mock(50 defaultAnswer = CALLS_REAL_METHODS,51 useConstructor = UseConstructor.withArguments(aemDb, api, fileManager, manifestManager, testScope)52 )53 }54 // region Translations55 @Test56 fun `processDownloadedTranslations()`() = testScope.runTest {57 val translation = mock<Translation>()58 val translations = listOf(translation)59 val uri = mock<Uri>()60 val manifest = mock<Manifest> { on { aemImports } doReturn listOf(uri) }61 val repository = aemDb.translationRepository().stub {62 onBlocking { isProcessed(any()) } doReturn false63 }64 whenever(manifestManager.getManifest(translation)) doReturn manifest65 whenever(articleManager.syncAemImportsFromManifest(any(), any())) doReturn null66 articleManager.processDownloadedTranslations(translations)67 testScheduler.advanceUntilIdle()68 verify(repository).isProcessed(translation)69 verify(manifestManager).getManifest(translation)70 verify(repository).addAemImports(translation, manifest.aemImports)71 verify(articleManager).syncAemImportsFromManifest(eq(manifest), any())72 verify(repository).removeMissingTranslations(translations)73 verifyNoMoreInteractions(repository)74 }75 @Test76 fun `processDownloadedTranslations() - Don't process already processed translations`() = testScope.runTest {77 val translation = mock<Translation>()78 val translations = listOf(translation)79 val repository = aemDb.translationRepository().stub {80 onBlocking { isProcessed(translation) } doReturn true81 }82 articleManager.processDownloadedTranslations(translations)83 verify(repository).isProcessed(translation)84 verify(repository).removeMissingTranslations(translations)85 verifyNoInteractions(manifestManager)86 verify(articleManager, never()).syncAemImportsFromManifest(any(), any())87 verifyNoMoreInteractions(repository)88 }89 @Test90 fun `processDownloadedTranslations() - Don't process without a downloaded manifest`() = testScope.runTest {91 val translation = mock<Translation>()92 val translations = listOf(translation)93 val repository = aemDb.translationRepository().stub {94 onBlocking { isProcessed(translation) } doReturn false95 }96 whenever(manifestManager.getManifest(translation)) doReturn null97 articleManager.processDownloadedTranslations(translations)98 verify(repository).isProcessed(translation)99 verify(manifestManager).getManifest(translation)100 verify(repository, never()).addAemImports(any(), any())101 verify(articleManager, never()).syncAemImportsFromManifest(any(), any())102 verify(repository).removeMissingTranslations(translations)103 verifyNoMoreInteractions(repository)104 }105 // endregion Translations106 // region Download Resource107 @Test108 fun testDownloadResource() = testScope.runTest {109 val uri = mock<Uri>()110 val resource = Resource(uri)111 val response = ByteArray(0).toResponseBody()112 whenever(aemDb.resourceDao().find(uri)) doReturn resource113 whenever(api.downloadResource(uri)) doReturn Response.success(response)114 articleManager.downloadResource(uri, false)115 verify(aemDb.resourceDao()).find(uri)116 verify(api).downloadResource(uri)117 verify(fileManager).storeResponse(response, resource)118 }119 @Test120 fun `Don't download resource if it doesn't exist in the database`() = testScope.runTest {121 val uri = mock<Uri>()122 articleManager.downloadResource(uri, false)123 verify(aemDb.resourceDao()).find(uri)124 verifyNoInteractions(api)125 }126 @Test127 fun `Don't download resource if it has already been downloaded`() = testScope.runTest {128 val uri = mock<Uri>()129 val resource = mock<Resource> { on { needsDownload() } doReturn false }130 whenever(aemDb.resourceDao().find(uri)).thenReturn(resource)131 articleManager.downloadResource(uri, false)132 verify(aemDb.resourceDao()).find(uri)133 verify(resource).needsDownload()134 verifyNoInteractions(api)135 }136 // endregion Download Resource137 @Test138 fun testRoundTimestamp() {139 assertEquals(15000, 15234L.roundTimestamp(1000))140 }141}...

Full Screen

Full Screen

MockitoCodeGenerator.kt

Source:MockitoCodeGenerator.kt Github

copy

Full Screen

1package com.mitteloupe.testit.generator.mocking2import com.mitteloupe.testit.generator.formatting.Formatting3import com.mitteloupe.testit.generator.formatting.toNonNullableKotlinString4import com.mitteloupe.testit.model.ClassMetadata5import com.mitteloupe.testit.model.DataType6class MockitoCodeGenerator(7 mockableTypeQualifier: MockableTypeQualifier,8 formatting: Formatting,9 mockitoRuleVariableName: String10) : MockerCodeGenerator(mockableTypeQualifier, formatting) {11 private var hasMockedConstructorParameters = false12 private var isParameterizedTest = false13 override val testClassBaseRunnerAnnotation: String = "@RunWith(MockitoJUnitRunner::class)"14 override val mockingRule =15 "${indent()}@get:Rule\n" +16 "${indent()}val $mockitoRuleVariableName: MethodRule = MockitoJUnit.rule()"17 override val knownImports = mapOf(18 "MockitoJUnitRunner" to "org.mockito.junit.MockitoJUnitRunner",19 "MockitoJUnit" to "org.mockito.junit.MockitoJUnit",20 "Mock" to "org.mockito.Mock",21 "mock" to "org.mockito.kotlin.mock",22 "Mockito" to "org.mockito.Mockito",23 "UseConstructor" to "org.mockito.kotlin.UseConstructor"24 ) + super.knownImports25 override val setUpStatements: String? = null26 override fun reset() {27 _requiredImports.clear()28 }29 override fun getConstructorMock(parameterName: String, parameterType: DataType) =30 "${indent()}@Mock\n" +31 "${indent()}lateinit var $parameterName: ${parameterType.toNonNullableKotlinString()}"32 override fun getMockedInstance(variableType: DataType) =33 "mock<${variableType.toNonNullableKotlinString()}>()"34 override fun getAbstractClassUnderTest(classUnderTest: ClassMetadata) =35 "mock(defaultAnswer = Mockito.CALLS_REAL_METHODS${constructorArgumentsForAbstract(classUnderTest)})"36 override fun setIsParameterizedTest() {37 super.setIsParameterizedTest()38 isParameterizedTest = true39 addMockRuleIfNeeded()40 }41 override fun setHasMockedConstructorParameters(classUnderTest: ClassMetadata) {42 _requiredImports.add("RunWith")43 _requiredImports.add("MockitoJUnitRunner")44 _requiredImports.add("Mock")45 if (classUnderTest.isAbstract && classUnderTest.constructorParameters.isNotEmpty()) {46 _requiredImports.add("UseConstructor")47 }48 hasMockedConstructorParameters = true49 addMockRuleIfNeeded()50 }51 private fun addMockRuleIfNeeded() {52 if (isParameterizedTest && hasMockedConstructorParameters) {53 _requiredImports.add("Rule")54 _requiredImports.add("MethodRule")55 _requiredImports.add("MockitoJUnit")56 }57 }58 override fun setHasMockedFunctionParameters() {59 setInstantiatesMocks()60 }61 override fun setHasMockedFunctionReturnValues() {62 setInstantiatesMocks()63 }64 override fun setIsAbstractClassUnderTest() {65 setInstantiatesMocks()66 _requiredImports.add("Mockito")67 }68 private fun setInstantiatesMocks() {69 _requiredImports.add("mock")70 }71 private fun constructorArgumentsForAbstract(classUnderTest: ClassMetadata) =72 if (classUnderTest.constructorParameters.isEmpty()) {73 ""74 } else {75 val arguments =76 classUnderTest.constructorParameters.joinToString(", ") { parameter -> parameter.name }77 ", useConstructor = UseConstructor.withArguments($arguments)"78 }79}...

Full Screen

Full Screen

ItemDaoHelperTest.kt

Source:ItemDaoHelperTest.kt Github

copy

Full Screen

...6import kotlinx.coroutines.ExperimentalCoroutinesApi7import kotlinx.coroutines.test.runTest8import org.junit.Test9import org.junit.runner.RunWith10import org.mockito.Mock11import org.mockito.Mockito.verify12import org.mockito.junit.MockitoJUnitRunner13import org.mockito.kotlin.UseConstructor14import org.mockito.kotlin.mock15@OptIn(ExperimentalCoroutinesApi::class)16@RunWith(MockitoJUnitRunner::class)17class ItemDaoHelperTest {18 @Mock19 lateinit var pagingDao: BaseGetPagingSourceDao<Any>20 @Mock21 lateinit var itemDao: BaseDao<Any>22 @Mock23 lateinit var remoteKeyDao: RemoteKeyDao24 private val mockTransactionManager = MockTransactionManager()25 @Test26 fun `save valid items and remoteKeys verify functions usage`() = runTest {27 val daoHelper = getSaveItemsWithRemoteKeysDaoHelper()28 val items = EmulatedData.characterList29 val remoteKeys = EmulatedData.remoteKeyList30 daoHelper.save(items, remoteKeys)31 verify(itemDao).insertItems(items)32 verify(remoteKeyDao).insertItems(remoteKeys)33 }34 @Test35 fun `save empty data verify all functions triggered`() = runTest {36 val daoHelper = getSaveItemsWithRemoteKeysDaoHelper()37 daoHelper.save(emptyList(), emptyList())38 verify(itemDao).insertItems(emptyList())39 verify(remoteKeyDao).insertItems(emptyList())40 }41 @Test(expected = IllegalArgumentException::class)42 fun `save items and remoteKeys with different data size throws exception`() = runTest {43 val daoHelper = getSaveItemsWithRemoteKeysDaoHelper()44 daoHelper.save(EmulatedData.characterList, emptyList())45 }46 private fun getSaveItemsWithRemoteKeysDaoHelper() : SaveItemsWithRemoteKeysDaoHelper<Any> =47 mock(useConstructor = UseConstructor.withArguments(48 itemDao, remoteKeyDao, mockTransactionManager49 ))50 @Test51 fun `clear item dao and remoteKey dao`() = runTest {52 val clearDaoHelper = ClearAllItemsAndKeysDaoHelper(itemDao, remoteKeyDao, mockTransactionManager)53 clearDaoHelper.clearTables()54 verify(itemDao).clear()55 verify(remoteKeyDao).clear()56 }57 @Test58 fun `get paging source`() = runTest {59 val pagingDaoHelper: GetPagingSourceDaoHelper<Any> = mock(60 useConstructor = UseConstructor.withArguments(pagingDao)61 )62 pagingDaoHelper.getPagingSource()63 verify(pagingDao).getPagingSource()64 }65}...

Full Screen

Full Screen

FeedActivityTests.kt

Source:FeedActivityTests.kt Github

copy

Full Screen

...20import org.koin.core.module.Module21import org.koin.dsl.module22import org.koin.test.KoinTest23import org.koin.test.get24import org.mockito.kotlin.UseConstructor25import org.mockito.kotlin.mock26/**27 * Created by Vdovicenco Alexandr on 04/19/2021.28 */29@RunWith(AndroidJUnit4::class)30class FeedActivityTests: KoinTest {31 lateinit var mockModule: Module32 @Before33 fun setup() {34 mockModule = module(override = true) {35 single<FeedOutput>(override = true) { (view: FeedInput) ->36 mock<FeedPresenter>(useConstructor = UseConstructor.withArguments(view, get<APIClient>()))37 }38 single<APIClient> { mock() }39 }40 loadKoinModules(mockModule)41 }42 @After43 fun tearDown() {44 unloadKoinModules(mockModule)45 }46 @Test47 fun checkFeedLoading() {48 val feedItemStub = FeedItem("", null, null)49 ActivityScenario.launch(FeedActivity::class.java)50 // Init expected result51 val expectedDataSet = arrayOf(feedItemStub)52 val mockPresenter = get<FeedOutput>() as FeedPresenter53 mockPresenter.view.updateUI(expectedDataSet)54 onView(withId(R.id.feed_recycler_view)).check(matches(isDisplayed()))55 }56}

Full Screen

Full Screen

AuthActivityTest.kt

Source:AuthActivityTest.kt Github

copy

Full Screen

...15import org.junit.runner.RunWith16import org.koin.core.context.GlobalContext.loadKoinModules17import org.koin.core.module.Module18import org.koin.dsl.module19import org.mockito.kotlin.UseConstructor20import org.mockito.kotlin.mock21@RunWith(AndroidJUnit4::class)22class AuthActivityTest: TestCase() {23 lateinit var mockModule: Module24 @Before25 fun setup() {26 mockModule = module(override = true) {27 single<AuthOutput>(override = true) { (view: AuthInput) ->28 mock<AuthPresenter>(useConstructor = UseConstructor.withArguments(view, get<APIClient>()))29 }30 single<APIClient> { mock() }31 }32 loadKoinModules(mockModule)33 }34 @get:Rule35 val activityRule = ActivityScenarioRule(AuthActivity::class.java)36 @Test37 fun test_validateEditText() {38 onView(withId(R.id.userLogin)).perform(typeText("test-string")).check(matches(withText("test-string")))39 }40}...

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1 fun test2() {2 val mock = mock<UseConstructor> {3 on { it.name } doReturn "test"4 }5 println(mock.name)6 }7 fun test3() {8 val mock = mock<UseConstructor> {9 on { it.name } doReturn "test"10 }11 println(mock.name)12 }13 package com.example;14 import org.junit.jupiter.api.Test;15 import org.mockito.Mockito;16 public class TestMockito {17 public void test() {18 UseConstructor mock = Mockito.mock(UseConstructor.class);19 Mockito.when(mock.getName()).thenReturn("test");20 System.out.println(mock.getName());21 }22 }23I have also posted this question on StackOverflow: [Mockito Kotlin - mock method of org.mockito.kotlin.UseConstructor class returns the same output for all the tests](stackoverflow.com/questions/69...)

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1 fun testMockMethodOfUseConstructorClass() {2 val mock = mock<UseConstructor> {3 on { useConstructor() } doReturn "Hello World"4 }5 assertEquals("Hello World", mock.useConstructor())6 }7}

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1 fun testMockWithConstructor() {2 val mock = mock<UseConstructor> {3 on { it.name } doReturn "mocked name"4 }5 assertEquals("mocked name", mock.name)6 }7 fun testMockWithConstructor() {8 val mock = mock<UseConstructor> {9 on { it.name } doReturn "mocked name"10 }11 assertEquals("mocked name", mock.name)12 }13 fun testMockWithConstructor() {14 val mock = mock<UseConstructor> {15 on { it.name } doReturn "mocked name"16 }17 assertEquals("mocked name", mock.name)18 }19 fun testMockWithConstructor() {20 val mock = mock<UseConstructor> {21 on { it.name } doReturn "mocked name"22 }23 assertEquals("mocked name", mock.name)24 }25 fun testMockWithConstructor() {26 val mock = mock<UseConstructor> {27 on { it.name } doReturn "mocked name"28 }29 assertEquals("mocked name", mock.name)30 }31 fun testMockWithConstructor() {32 val mock = mock<UseConstructor> {33 on { it.name } doReturn "mocked name"34 }35 assertEquals("mocked name", mock.name)36 }37 fun testMockWithConstructor() {38 val mock = mock<UseConstructor> {39 on { it.name } doReturn "mocked name"40 }41 assertEquals("mocked name", mock.name)42 }43 fun testMockWithConstructor() {44 val mock = mock<UseConstructor> {45 on { it.name } doReturn "mocked name"46 }47 assertEquals("mocked name", mock.name)48 }

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1 fun testUseConstructor() {2 val useConstructor = UseConstructor("test")3 useConstructor.useConstructor()4 }5 fun testUseMethod() {6 val useMethod = UseMethod("test")7 useMethod.useMethod()8 }9 fun testUseProperty() {10 val useProperty = UseProperty("test")11 useProperty.useProperty()12 }13 fun testUseLambda() {14 val useLambda = UseLambda("test")15 useLambda.useLambda()16 }17}

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))2 mock.print()3 }4 fun testMockitoKotlinWithUseConstructor() {5 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))6 mock.print()7 }8 fun testMockitoKotlinWithUseConstructorAndArgument() {9 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))10 mock.print("Hello")11 }12 fun testMockitoKotlinWithUseConstructorAndArgument2() {13 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))14 mock.print("Hello")15 }16 fun testMockitoKotlinWithUseConstructorAndArgument3() {17 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))18 mock.print("Hello")19 }20 fun testMockitoKotlinWithUseConstructorAndArgument4() {21 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))22 mock.print("Hello")23 }24 fun testMockitoKotlinWithUseConstructorAndArgument5() {25 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))26 mock.print("Hello")27 }28 fun testMockitoKotlinWithUseConstructorAndArgument6() {29 val mock = mock<UseConstructor>(useConstructor.constructor(String::class.java))30 mock.print("Hello")31 }32 fun testMockitoKotlinWithUseConstructorAndArgument7() {

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1 fun testMockitoKotlinUseConstructor() {2 val mock = mock<MockitoKotlinUseConstructor>(3 useConstructor = UseConstructor.withArguments("abc", 123)4 mock.print()5 verify(mock).print()6 }7 fun testMockitoKotlinUseConstructor1() {8 val mock = mock<MockitoKotlinUseConstructor>(9 useConstructor = UseConstructor.withArguments("abc", 123)10 mock.print()11 verify(mock).print()12 }13 fun testMockitoKotlinUseConstructor2() {14 val mock = mock<MockitoKotlinUseConstructor>(15 useConstructor = UseConstructor.withArguments("abc", 123)16 mock.print()17 verify(mock).print()18 }19 fun testMockitoKotlinUseConstructor3() {20 val mock = mock<MockitoKotlinUseConstructor>(21 useConstructor = UseConstructor.withArguments("abc", 123)22 mock.print()23 verify(mock).print()24 }25 fun testMockitoKotlinUseConstructor4() {26 val mock = mock<MockitoKotlinUseConstructor>(27 useConstructor = UseConstructor.withArguments("abc", 123)28 mock.print()29 verify(mock).print()30 }31 fun testMockitoKotlinUseConstructor5() {32 val mock = mock<MockitoKotlinUseConstructor>(33 useConstructor = UseConstructor.withArguments("abc", 123)34 mock.print()35 verify(mock).print()36 }37 fun testMockitoKotlinUseConstructor6() {38 val mock = mock<MockitoKotlinUseConstructor>(

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1val mockConstructor = mock<UseConstructor>(constructor = UseConstructor::class.constructors.first()) {2 on { it.getSomething() } doReturn "mocked constructor"3}4val mockClass = mock<MockClass> {5 on { it.getSomething() } doReturn "mocked class"6 on { it.getUseConstructor() } doReturn mockConstructor7}8println(mockClass.getUseConstructor().getSomething())9println(mockClass.getSomething())10val mockConstructor = mock<UseConstructor>(constructor = UseConstructor::class.constructors.first()) {11 on { it.getSomething() } doReturn "mocked constructor"12}13val mockClass = mock<MockClass> {14 on { it.getSomething() } doReturn "mocked class"15 on { it.getUseConstructor() } doReturn mockConstructor16}17println(mockClass.getUseConstructor().getSomething())18println(mockClass.getSomething())

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 UseConstructor

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful