How to use given method of org.mockito.kotlin.BDDMockito class

Best Mockito-kotlin code snippet using org.mockito.kotlin.BDDMockito.given

AsyncRetryExecutorManyFailuresKotlinTest.kt

Source:AsyncRetryExecutorManyFailuresKotlinTest.kt Github

copy

Full Screen

...30class AsyncRetryExecutorManyFailuresKotlinTest : AbstractRetryKotlinTest() {31 @Test32 @Throws(Exception::class)33 fun shouldRethrowIfFirstFewExecutionsThrow() {34 //given35 val executor = AsyncRetryExecutor(schedulerMock).withMaxRetry(2)36 BDDMockito37 .given<String>(serviceMock.sometimesFails())38 .willThrow(IllegalStateException(DON_T_PANIC))39 //when40 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}...

Full Screen

Full Screen

AsyncRetryExecutorManualAbortKotlinTest.kt

Source:AsyncRetryExecutorManualAbortKotlinTest.kt Github

copy

Full Screen

...30class AsyncRetryExecutorManualAbortKotlinTest : AbstractRetryKotlinTest() {31 @Test32 @Throws(Exception::class)33 fun shouldRethrowIfFirstExecutionThrowsAnExceptionAndNoRetry() {34 // given35 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}...

Full Screen

Full Screen

BDDMockito.kt

Source:BDDMockito.kt Github

copy

Full Screen

...29import org.mockito.kotlin.internal.SuspendableAnswer30import org.mockito.stubbing.Answer31import kotlin.reflect.KClass32/**33 * Alias for [BDDMockito.given].34 */35fun <T> given(methodCall: T): BDDMockito.BDDMyOngoingStubbing<T> {36 return BDDMockito.given(methodCall)37}38/**39 * Alias for [BDDMockito.given] with a lambda.40 */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/**...

Full Screen

Full Screen

FuncionarioServiceTest.kt

Source:FuncionarioServiceTest.kt Github

copy

Full Screen

...28 private val id: String = "1"29 @BeforeEach30 @Throws(Exception::class)31 fun setUp() {32 BDDMockito.given(funcionarioRepository?.save(Mockito.any(Funcionario::class.java)))33 .willReturn(funcionario())34 BDDMockito.given(funcionarioRepository?.findById(id)).willReturn(Optional.of(funcionario()))35 BDDMockito.given(funcionarioRepository?.findByEmail(email)).willReturn(funcionario())36 BDDMockito.given(funcionarioRepository?.findByCpf(cpf)).willReturn(funcionario())37 }38 @Test39 fun testPersistirFuncionario() {40 val funcionario: Funcionario? = this.funcionarioService?.persistir(funcionario())41 Assertions.assertNotNull(funcionario)42 }43 @Test44 fun testBuscarFuncionarioPorId() {45 val funcionario: Funcionario? = this.funcionarioService?.buscarPorId(id)46 Assertions.assertNotNull(funcionario)47 }48 @Test49 fun testBuscarFuncionarioPorEmail() {50 val funcionario: Funcionario? = this.funcionarioService?.buscarPorEmail(email)...

Full Screen

Full Screen

EmployeeServiceTest.kt

Source:EmployeeServiceTest.kt Github

copy

Full Screen

...26 private val document: String = "00000000000000"27 private val id: String = "1"28 @BeforeEach29 fun setup() {30 BDDMockito.given(employeeRepository?.save(Mockito.any(Employee::class.java))).willReturn(employee())31 BDDMockito.given(employeeRepository?.findByDocument(document)).willReturn(employee())32 BDDMockito.given(employeeRepository?.findByEmail(email)).willReturn(employee())33 BDDMockito.given(employeeRepository?.findById(id)).willReturn(Optional.of(employee()))34 }35 @Test36 fun findByDocumentTest() {37 val employee = employeeService?.findByDocument(document)38 Assertions.assertNotNull(employee)39 }40 @Test41 fun findByEmailTest() {42 val employee = employeeService?.findByEmail(email)43 Assertions.assertNotNull(employee)44 }45 @Test46 fun findByIdTest() {47 val employee = employeeService?.findById(id)...

Full Screen

Full Screen

EmployeeListViewModelTest.kt

Source:EmployeeListViewModelTest.kt Github

copy

Full Screen

...14import org.junit.Before15import org.junit.Rule16import org.junit.Test17import org.junit.runner.RunWith18import org.mockito.BDDMockito.given19import org.mockito.BDDMockito.verify20import org.mockito.Mock21import org.mockito.MockitoAnnotations22import org.mockito.junit.MockitoJUnitRunner23import kotlin.test.assertEquals24import kotlin.test.assertNotNull25@ExperimentalCoroutinesApi26@RunWith(MockitoJUnitRunner::class)27class EmployeeListViewModelTest {28 @get:Rule29 var instantTaskExecutorRule = InstantTaskExecutorRule()30 @get:Rule31 var mainCoroutinesRule = MainCoroutinesRule()32 private lateinit var viewModel: EmployeeListViewModel33 private val _res: MutableLiveData<Resource<List<Employee>>> = MutableLiveData()34 val res: LiveData<Resource<List<Employee>>> = _res35 @Mock36 lateinit var repository: EmployeeRepository37 @Mock38 lateinit var employeeListResponseObserver: Observer<Resource<List<Employee>>>39 @Before40 fun setup() {41 MockitoAnnotations.openMocks(this)42 viewModel = EmployeeListViewModel(repository)43 }44 @Test45 fun `return employee list success`() {46 runTest {47 val flow = flow<Resource<List<Employee>>> {48 emit(Resource.loading(null))49 }50 flow.collect {51 _res.value = it52 }53 viewModel.employees.observeForever(employeeListResponseObserver)54 given(repository.getEmployeeList()).willReturn(flow)55 verify(repository).getEmployeeList()56 viewModel.getAllEmployees()57 assertNotNull(viewModel.employees.value)58 assertEquals(res.value, viewModel.employees.getOrAwaitValueTest())59 }60 }61}...

Full Screen

Full Screen

LancamentoServiceTest.kt

Source:LancamentoServiceTest.kt Github

copy

Full Screen

...26 @BeforeEach27 @Throws(Exception::class)28 fun setUp() {29 BDDMockito30 .given<Page<Lancamento>>(lancamentoRepository?.findByFuncionarioId(id, PageRequest.of(0, 10)))31 .willReturn(PageImpl(ArrayList<Lancamento>()))32 BDDMockito.given(lancamentoRepository?.findById("1")).willReturn(Optional.of(lancamento()))33 BDDMockito.given(lancamentoRepository?.save(Mockito.any(Lancamento::class.java)))34 .willReturn(lancamento())35 }36 @Test37 fun testBuscarFuncionarioPorFuncionarioId(){38 val lancamento: Page<Lancamento>? = this.lancamentoService?.buscarPorFuncionarioId(id,PageRequest.of(0,10))39 Assertions.assertNotNull(lancamento)40 }41 @Test42 fun testBuscarLancamentoPorId(){43 val lancamento: Lancamento? = this.lancamentoService?.buscarPorId(id)44 Assertions.assertNotNull(lancamento)45 }46 @Test47 fun testPersistirLancamento(){...

Full Screen

Full Screen

MessageServiceTest.kt

Source:MessageServiceTest.kt Github

copy

Full Screen

...5import org.junit.jupiter.api.Test6import org.junit.jupiter.api.extension.ExtendWith7import org.mockito.BDDMockito.anyString8import org.mockito.BDDMockito.atLeastOnce9import org.mockito.BDDMockito.given10import org.mockito.BDDMockito.verify11import org.mockito.Mock12import org.mockito.junit.jupiter.MockitoExtension13import reactor.core.publisher.Mono14import reactor.kotlin.core.publisher.toFlux15import reactor.kotlin.core.publisher.toMono16import reactor.kotlin.test.test17/**18 * Created by wonwoo on 2016. 10. 27..19 */20@ExtendWith(MockitoExtension::class)21class MessageServiceTest(@Mock private val messageRepository: MessageRepository) {22 private lateinit var messageService: MessageService23 private val account = Account("wonwoo", "pw")24 @BeforeEach25 fun setup() {26 messageService = MessageService(messageRepository)27 }28 @Test29 fun findAll() {30 val messages = listOf(Message(message = "test message", account = account)).toFlux()31 given(messageRepository.findAll()).willReturn(messages)32 val findAllMessages = messageService.findAll()33 findAllMessages.test().assertNext {34 assertThat(it.message).isEqualTo("test message")35 }.verifyComplete()36 }37 @Test38 fun save() {39 val message = Message(message = "test message", account = account)40 given(messageRepository.save(message)).willReturn(message.toMono())41 val saveMessage = messageService.save(message)42 saveMessage.test().assertNext {43 assertThat(it.message).isEqualTo("test message")44 }.verifyComplete()45 }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}...

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 BDDMockito

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful