Best Mockito-kotlin code snippet using org.mockito.kotlin.BDDMockito.then
AsyncRetryExecutorManyFailuresKotlinTest.kt
Source:AsyncRetryExecutorManyFailuresKotlinTest.kt
...40 val promise = executor.getWithRetry { serviceMock.sometimesFails() }41 promise.success {42 println("Success")43 }44// //then45// promise.ready()46// assertThat(promise.isFailure()).isTrue()47// try {48// promise.get()49// failBecauseExceptionWasNotThrown(IllegalStateException::class.java)50// } catch (t: ExecutionException) {51// val actualCause = t.cause!!52// assertThat(actualCause).isInstanceOf(IllegalStateException::class.java)53// assertThat(actualCause.message).isEqualTo(DON_T_PANIC)54// }55 }56 @Test57 @Throws(Exception::class)58 fun shouldRetryAfterManyExceptionsAndReturnValue() {59 //given60 val executor = AsyncRetryExecutor(schedulerMock)61 BDDMockito62 .given<String>(serviceMock.sometimesFails())63 .willThrow(IllegalStateException::class.java,64 IllegalStateException::class.java,65 IllegalStateException::class.java)66 .willReturn("Foo")67 //when68 val promise = executor.getWithRetry { serviceMock.sometimesFails() }69 //then70 assertThat(promise.get()).isEqualTo("Foo")71 }72 @Test73 @Throws(Exception::class)74 fun shouldSucceedWhenTheSameNumberOfRetriesAsFailuresAllowed() {75 //given76 val executor = AsyncRetryExecutor(schedulerMock).withMaxRetry(3)77 BDDMockito78 .given<String>(serviceMock.sometimesFails())79 .willThrow(IllegalStateException::class.java,80 IllegalStateException::class.java,81 IllegalStateException::class.java)82 .willReturn("Foo")83 //when84 val promise = executor.getWithRetry { serviceMock.sometimesFails() }85 //then86 assertThat(promise.get()).isEqualTo("Foo")87 }88 @Test89 @Throws(Exception::class)90 fun shouldRetryManyTimesIfFirstExecutionsThrowException() {91 //given92 val executor = AsyncRetryExecutor(schedulerMock)93 BDDMockito94 .given<String>(serviceMock.sometimesFails())95 .willThrow(IllegalStateException::class.java,96 IllegalStateException::class.java,97 IllegalStateException::class.java)98 .willReturn("Foo")99 //when100 executor.getWithRetry { serviceMock.sometimesFails() }101 //then102 verify<FaultyService>(serviceMock, times(4)).sometimesFails()103 }104 @Test105 @Throws(Exception::class)106 fun shouldScheduleRetryWithDefaultDelay() {107 //given108 val executor = AsyncRetryExecutor(schedulerMock)109 BDDMockito110 .given<String>(serviceMock.sometimesFails())111 .willThrow(IllegalStateException::class.java,112 IllegalStateException::class.java,113 IllegalStateException::class.java)114 .willReturn("Foo")115 //when116 executor.getWithRetry<String>(Callable<String> { serviceMock.sometimesFails() })117 //then118 val inOrder = inOrder(schedulerMock)119 inOrder.verify(schedulerMock).schedule(notNullRunnable(), eq(0L), millis())120 inOrder.verify(schedulerMock, times(3)).schedule(notNullRunnable(), eq(DEFAULT_PERIOD_MILLIS), millis())121 inOrder.verifyNoMoreInteractions()122 }123 @Test124 @Throws(Exception::class)125 fun shouldPassCorrectRetryCountToEachInvocationInContext() {126 //given127 val executor = AsyncRetryExecutor(schedulerMock)128 BDDMockito.given(serviceMock.calculateSum(0)).willThrow(IllegalStateException::class.java)129 BDDMockito.given(serviceMock.calculateSum(1)).willThrow(IllegalStateException::class.java)130 BDDMockito.given(serviceMock.calculateSum(2)).willThrow(IllegalStateException::class.java)131 BDDMockito.given(serviceMock.calculateSum(3)).willReturn(BigDecimal.ONE)132 //when133 executor.getWithRetry { ctx -> serviceMock.calculateSum(ctx.retryCount) }134 //then135 val order = inOrder(serviceMock)136 order.verify(serviceMock).calculateSum(0)137 order.verify(serviceMock).calculateSum(1)138 order.verify(serviceMock).calculateSum(2)139 order.verify(serviceMock).calculateSum(3)140 order.verifyNoMoreInteractions()141 }142}...
AuthControllerTest.kt
Source:AuthControllerTest.kt
1package com.pinocchio.santaclothes.apiserver.controller2import com.pinocchio.santaclothes.apiserver.authorization.TokenManager3import com.pinocchio.santaclothes.apiserver.controller.dto.LoginRequest4import com.pinocchio.santaclothes.apiserver.controller.dto.RefreshRequest5import com.pinocchio.santaclothes.apiserver.controller.dto.RegisterRequest6import com.pinocchio.santaclothes.apiserver.entity.AccountType7import com.pinocchio.santaclothes.apiserver.exception.DatabaseException8import com.pinocchio.santaclothes.apiserver.exception.ExceptionReason9import com.pinocchio.santaclothes.apiserver.exception.TokenInvalidException10import com.pinocchio.santaclothes.apiserver.service.UserService11import com.pinocchio.santaclothes.apiserver.test.ApiTest12import io.restassured.http.ContentType13import io.restassured.module.kotlin.extensions.Given14import io.restassured.module.kotlin.extensions.Then15import io.restassured.module.kotlin.extensions.When16import org.junit.jupiter.api.Test17import org.mockito.BDDMockito18import org.mockito.Mockito.times19import org.mockito.Mockito.verify20import org.springframework.boot.test.mock.mockito.MockBean21import java.util.UUID22class AuthControllerTest : ApiTest() {23 @MockBean24 lateinit var userService: UserService25 @MockBean26 lateinit var tokenManager: TokenManager27 @Test28 fun register() {29 val token = "token"30 val name = "name"31 val accountType = AccountType.KAKAO32 val registerRequest = RegisterRequest(token, name, accountType)33 Given {34 contentType(ContentType.JSON)35 body(registerRequest)36 } When {37 post("/auth/register")38 } Then {39 statusCode(201)40 }41 verify(userService, times(1)).register(token, name, accountType)42 }43 @Test44 fun registerExistUser() {45 val token = "token"46 val name = "name"47 val accountType = AccountType.KAKAO48 val registerRequest = RegisterRequest(token, name, accountType)49 BDDMockito.given(userService.register(token, name, accountType))50 .willThrow(DatabaseException(ExceptionReason.DUPLICATE_ENTITY))51 Given {52 contentType(ContentType.JSON)53 body(registerRequest)54 } When {55 post("/auth/register")56 } Then {57 statusCode(409)58 }59 }60 @Test61 fun login() {62 val userToken = "token"63 val deviceToken = "deviceToken"64 val loginRequest = LoginRequest(userToken, deviceToken)65 Given {66 contentType(ContentType.JSON)67 body(loginRequest)68 } When {69 post("/auth/login")70 } Then {71 statusCode(200)72 }73 verify(userService, times(1)).login(userToken, deviceToken)74 }75 @Test76 fun loginWithNoTokenThrows() {77 val userToken = "token"78 val deviceToken = "deviceToken"79 val loginRequest = LoginRequest(userToken, deviceToken)80 BDDMockito.given(81 userService.login(82 userToken,83 deviceToken84 )85 ).willThrow(TokenInvalidException(ExceptionReason.USER_TOKEN_NOT_EXISTS))86 Given {87 contentType(ContentType.JSON)88 body(loginRequest)89 } When {90 post("/auth/login")91 } Then {92 statusCode(400)93 }94 }95 @Test96 fun refreshAccessToken() {97 val refreshToken = UUID.randomUUID()98 val refreshRequest = RefreshRequest(refreshToken)99 Given {100 contentType(ContentType.JSON)101 body(refreshRequest)102 } When {103 put("/auth/accessToken")104 } Then {105 statusCode(200)106 }107 verify(tokenManager, times(1)).refreshAccessToken(refreshToken)108 }109 @Test110 fun refreshAccessTokenIsExpiredThrows() {111 val refreshToken = UUID.randomUUID()112 val refreshRequest = RefreshRequest(refreshToken)113 BDDMockito.given(tokenManager.refreshAccessToken(refreshToken))114 .willThrow(TokenInvalidException(ExceptionReason.INVALID_REFRESH_TOKEN))115 Given {116 contentType(ContentType.JSON)117 body(refreshRequest)118 } When {119 put("/auth/accessToken")120 } Then {121 statusCode(400)122 }123 }124}...
AsyncRetryExecutorManualAbortKotlinTest.kt
Source:AsyncRetryExecutorManualAbortKotlinTest.kt
...35 val executor = AsyncRetryExecutor(schedulerMock).dontRetry()36 BDDMockito.given(serviceMock.sometimesFails()).willThrow(IllegalStateException(DON_T_PANIC))37 // when38 val promise = executor.getWithRetry { serviceMock.sometimesFails() }39 // then40 promise.ready()41 assertThat(promise.isFailure()).isTrue()42 assertThat(promise.getError()).isInstanceOf(IllegalStateException::class.java)43 }44 @Test45 @Throws(Exception::class)46 fun shouldRetryAfterOneExceptionAndReturnValue() {47 // given48 val executor = AsyncRetryExecutor(schedulerMock)49 BDDMockito.given(serviceMock.sometimesFails()).willThrow(IllegalStateException::class.java).willReturn("Foo")50 // when51 val promise = executor.getWithRetry { serviceMock.sometimesFails() }52 // then53 assertThat(promise.get()).isEqualTo("Foo")54 }55 @Test56 @Throws(Exception::class)57 fun shouldSucceedWhenOnlyOneRetryAllowed() {58 // given59 val executor = AsyncRetryExecutor(schedulerMock).withMaxRetry(1)60 BDDMockito.given(serviceMock.sometimesFails()).willThrow(IllegalStateException::class.java).willReturn("Foo")61 // when62 val promise = executor.getWithRetry { serviceMock.sometimesFails() }63 // then64 assertThat(promise.get()).isEqualTo("Foo")65 }66 @Test67 @Throws(Exception::class)68 fun shouldRetryOnceIfFirstExecutionThrowsException() {69 // given70 val executor = AsyncRetryExecutor(schedulerMock)71 BDDMockito.given(serviceMock.sometimesFails()).willThrow(IllegalStateException::class.java).willReturn("Foo")72 // when73 executor.getWithRetry { serviceMock.sometimesFails() }74 // then75 verify<FaultyService>(serviceMock, times(2)).sometimesFails()76 }77 @Test78 @Throws(Exception::class)79 fun shouldScheduleRetryWithDefaultDelay() {80 // given81 val executor = AsyncRetryExecutor(schedulerMock)82 BDDMockito.given(serviceMock.sometimesFails()).willThrow(IllegalStateException::class.java).willReturn("Foo")83 // when84 executor.getWithRetry { serviceMock.sometimesFails() }85 // then86 val order = inOrder(schedulerMock)87 order.verify(schedulerMock).schedule(notNullRunnable(), eq(0L), millis())88 order.verify(schedulerMock).schedule(notNullRunnable(), eq(DEFAULT_PERIOD_MILLIS), millis())89 order.verifyNoMoreInteractions()90 }91 @Test92 @Throws(Exception::class)93 fun shouldPassCorrectRetryCountToEachInvocationInContext() {94 //given95 val executor = AsyncRetryExecutor(schedulerMock)96 BDDMockito.given(serviceMock.calculateSum(0)).willThrow(IllegalStateException::class.java)97 BDDMockito.given(serviceMock.calculateSum(1)).willReturn(BigDecimal.ONE)98 //when99 executor.getWithRetry { ctx -> serviceMock.calculateSum(ctx.retryCount) }100 //then101 val order = inOrder(serviceMock)102 order.verify(serviceMock).calculateSum(0)103 order.verify(serviceMock).calculateSum(1)104 order.verifyNoMoreInteractions()105 }106}...
BDDMockito.kt
Source:BDDMockito.kt
...41fun <T> given(methodCall: () -> T): BDDMyOngoingStubbing<T> {42 return given(methodCall())43}44/**45 * Alias for [BDDMockito.then].46 */47fun <T> then(mock: T): BDDMockito.Then<T> {48 return BDDMockito.then(mock)49}50/**51 * Alias for [BDDMyOngoingStubbing.will]52 * */53infix fun <T> BDDMyOngoingStubbing<T>.will(value: Answer<T>): BDDMockito.BDDMyOngoingStubbing<T> {54 return will(value)55}56/**57 * Alias for [BBDMyOngoingStubbing.willAnswer], accepting a lambda.58 */59infix fun <T> BDDMyOngoingStubbing<T>.willAnswer(value: (InvocationOnMock) -> T?): BDDMockito.BDDMyOngoingStubbing<T> {60 return willAnswer { value(it) }61}62/**...
SMSAuthServiceTest.kt
Source:SMSAuthServiceTest.kt
...32 given(authRepository.searchAuth(mobile)).willReturn(actualAuth)33 given(authRepository.deleteAuth(mobile)).willReturn(true)34 // when35 authService.verifyAuth(mobile, inputAuth)36 // then37 verify(authRepository, times(1)).searchAuth(mobile)38 verify(authRepository, times(1)).deleteAuth(mobile)39 }40 @Test41 @DisplayName("문ìë¡ ì ì¡ë°ì ì¸ì¦ë²í¸ì ë¤ë¥¸ ë²í¸ë¥¼ ì
ë ¥íë©´ ì¸ì¦ì ì¤í¨íë©° AuthNotFoundException ì´ ë°ìí©ëë¤.")42 fun `verify auth number fail with incorrect auth number input`() {43 // given44 given(authRepository.searchAuth(mobile)).willReturn("123123")45 // when46 assertThrows<AuthNotFoundException> { authService.verifyAuth(mobile, inputAuth) }47 // then48 verify(authRepository, times(1)).searchAuth(mobile)49 verify(authRepository, never()).deleteAuth(mobile)50 }51}...
AsyncRetryExecutorHappyKotlinTest.kt
Source:AsyncRetryExecutorHappyKotlinTest.kt
...28 // given29 val executor = AsyncRetryExecutor(schedulerMock)30 // when31 executor.doWithRetry { ctx -> serviceMock.alwaysSucceeds(); }32 // then33 Mockito.verify(schedulerMock).schedule(notNullRunnable(), Matchers.eq(0L), millis())34 Mockito.verifyNoMoreInteractions(schedulerMock)35 }36 @Test37 fun shouldCallUserTaskOnlyOnceIfItDoesntFail() {38 // given39 val executor = AsyncRetryExecutor(schedulerMock)40 // when41 executor.doWithRetry { ctx -> serviceMock.alwaysSucceeds() }42 // then43 Mockito.verify(serviceMock).alwaysSucceeds()44 }45 @Test46 @Throws(Exception::class)47 fun shouldReturnResultOfFirstSucessfulCall() {48 // given49 val executor = AsyncRetryExecutor(schedulerMock)50 BDDMockito.given(serviceMock.alwaysSucceeds()).willReturn(42)51 // when52 val promise = executor.getWithRetry { serviceMock.alwaysSucceeds() }53 // then54 assertThat(promise.get()).isEqualTo(42)55 }56 @Test57 @Throws(Exception::class)58 fun shouldReturnEvenIfNoRetryPolicy() {59 // given60 val executor = AsyncRetryExecutor(schedulerMock).dontRetry()61 BDDMockito.given(serviceMock.alwaysSucceeds()).willReturn(42)62 // when63 val promise = executor.getWithRetry { serviceMock.alwaysSucceeds() }64 // then65 assertThat(promise.get()).isEqualTo(42)66 }67}...
MessageServiceTest.kt
Source:MessageServiceTest.kt
...46 @Test47 fun delete() {48 given(messageRepository.deleteById(anyString())).willReturn(Mono.empty())49 val delete = messageService.delete("test")50 delete.test().then {51 verify(messageRepository, atLeastOnce()).deleteById("test")52 }.verifyComplete()53 }54}...
KotlinRestControllerTest.kt
Source:KotlinRestControllerTest.kt
1package es.msanchez.frameworks.spring.boot.rest2import es.msanchez.frameworks.spring.boot.validator.KotlinValidator3import org.junit.jupiter.api.Test4import org.mockito.BDDMockito5import org.mockito.Mockito6internal class KotlinRestControllerTest {7 private val validator = Mockito.mock(KotlinValidator::class.java)8 private val controller = KotlinRestController(this.validator)9 @Test10 internal fun testIndex() {11 // Given12 // When13 this.controller.index()14 // Then15 BDDMockito.verify(this.validator).validate()16 }17}...
then
Using AI Code Generation
1val mock = mock<SomeClass>()2val mock = mock<SomeClass>()3val spy = spy<SomeClass>()4val spy = spy<SomeClass>()5val spy = spy<SomeClass>()6val spy = spy<SomeClass>()7val spy = spy<SomeClass>()8val spy = spy<SomeClass>()9val spy = spy<SomeClass>()10val spy = spy<SomeClass>()11val spy = spy<SomeClass>()12val spy = spy<SomeClass>()13val spy = spy<SomeClass>()14val spy = spy<SomeClass>()15val spy = spy<SomeClass>()16val spy = spy<SomeClass>()17val spy = spy<SomeClass>()18val spy = spy<SomeClass>()19val spy = spy<SomeClass>()
then
Using AI Code Generation
1import org.mockito.kotlin.whenever2}3}4}5}6}7}8}9}10}11}12}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!