Best Mockito code snippet using org.mockito.BDDMockito.willReturn
Source:AccountPageControllerTest.java
...181 MockitoAnnotations.initMocks(this);182 final Locale locale = new Locale("en");183 final List breadcrumbsList = new ArrayList();184 breadcrumbsList.add(breadcrumb);185 BDDMockito.given(accountBreadcrumbBuilder.getBreadcrumbs(Mockito.anyString())).willReturn(breadcrumbsList);186 BDDMockito.given(cmsPageService.getPageForLabelOrId(Mockito.anyString())).willReturn(contentPageModel);187 BDDMockito.given(pageTitleResolver.resolveContentPageTitle(Mockito.anyString())).willReturn(TITLE_FOR_PAGE);188 BDDMockito.given(Boolean.valueOf(page.containsAttribute(CMS_PAGE_MODEL))).willReturn(Boolean.TRUE);189 BDDMockito.given(page.asMap().get(CMS_PAGE_MODEL)).willReturn(abstractPageModel);190 BDDMockito.given(abstractPageModel.getMasterTemplate()).willReturn(pageTemplateModel);191 BDDMockito.given(cmsPageService.getFrontendTemplateName(pageTemplateModel)).willReturn(VIEW_FOR_PAGE);192 BDDMockito.given(checkoutFacade.getDeliveryCountries()).willReturn(Collections.singletonList(countryData));193 BDDMockito.given(userFacade.getTitles()).willReturn(Collections.singletonList(titleData));194 BDDMockito.given(customerData.getFirstName()).willReturn(FIRST_NAME);195 BDDMockito.given(customerData.getLastName()).willReturn(LAST_NAME);196 BDDMockito.given(customerData.getTitleCode()).willReturn(TITLE_CODE);197 BDDMockito.given(customerData.getUid()).willReturn(FIRST_NAME);198 BDDMockito.given(customerFacade.getCurrentCustomer()).willReturn(customerData);199 BDDMockito.given(i18NService.getCurrentLocale()).willReturn(locale);200 BDDMockito.given(i18NFacade.getRegionsForCountryIso(Mockito.anyString())).willReturn(Collections.singletonList(regionData));201 BDDMockito.given(messageSource.getMessage(Mockito.anyString(), Mockito.any(Object[].class), Mockito.eq(locale)))202 .willReturn("ANY STRING");203 BDDMockito.given(i18NFacade.getCountryForIsocode(Mockito.anyString())).willReturn(countryData);204 }205 private void setupAddressCreateEdit()206 {207 BDDMockito.doReturn(addressForm).when(accountController).getPreparedAddressForm();208 }209 private void createBasicAddressFields()210 {211 BDDMockito.given(addressForm.getFirstName()).willReturn(FIRST_NAME);212 BDDMockito.given(addressForm.getLastName()).willReturn(LAST_NAME);213 BDDMockito.given(addressForm.getLine1()).willReturn("LINE 1");214 BDDMockito.given(addressForm.getCountryIso()).willReturn("US");215 BDDMockito.given(addressForm.getRegionIso()).willReturn("NY");216 BDDMockito.given(addressForm.getPostcode()).willReturn("12345");217 }218 private void createEmailForm(final String email, final String password)219 {220 BDDMockito.given(emailForm.getEmail()).willReturn(email);221 BDDMockito.given(emailForm.getPassword()).willReturn(password);222 }223 private void setupExistingOrder()224 {225 BDDMockito.given(Integer.valueOf(paginationData.getNumberOfPages())).willReturn(Integer.valueOf(1));226 final ArrayList orderHistory = new ArrayList<OrderHistoryData>();227 orderHistory.add(orderHistoryData);228 searchList = new SearchPageData<OrderHistoryData>();229 searchList.setResults(orderHistory);230 searchList.setPagination(paginationData);231 }232 // Address Tests233 @Test234 public void shouldGetAddressForm()235 {236 BDDMockito.given(accountController.getCountries()).willReturn(Collections.singletonList(countryData));237 final String countryFragment = accountController.getCountryAddressForm("TEST_ADDRESS_CODE", TEST_COUNTRY_CODE, page);238 Mockito.verify(page).addAttribute("supportedCountries", accountController.getCountries());239 Mockito.verify(page).addAttribute("regions", i18NFacade.getRegionsForCountryIso(TEST_COUNTRY_CODE));240 Mockito.verify(page).addAttribute("country", TEST_COUNTRY_CODE);241 assertEquals(ControllerConstants.Views.Fragments.Account.CountryAddressForm, countryFragment);242 }243 @Test244 public void shouldGetAddressBook() throws CMSItemNotFoundException245 {246 BDDMockito.given(userFacade.getAddressBook()).willReturn(Collections.singletonList(addressData));247 final String addressBookPage = accountController.getAddressBook(page);248 Mockito.verify(page).addAttribute("addressData", Collections.singletonList(addressData));249 Mockito.verify(page).addAttribute("cmsPage", contentPageModel);250 Mockito.verify(page).addAttribute("pageTitle", TITLE_FOR_PAGE);251 assertEquals(FULL_VIEW_PATH, addressBookPage);252 }253 @Test254 public void shouldPrepareAddress()255 {256 final AddressForm addressForm = accountController.getPreparedAddressForm();257 assertEquals(FIRST_NAME, addressForm.getFirstName());258 assertEquals(LAST_NAME, addressForm.getLastName());259 assertEquals(TITLE_CODE, addressForm.getTitleCode());260 }261 @Test262 public void shouldGetAddAddress() throws CMSItemNotFoundException263 {264 setupAddressCreateEdit();265 final String addAddressPage = accountController.addAddress(page);266 Mockito.verify(page).addAttribute("countryData", Collections.singletonList(countryData));267 Mockito.verify(page).addAttribute("titleData", Collections.singletonList(titleData));268 Mockito.verify(page).addAttribute("addressForm", addressForm);269 Mockito.verify(page).addAttribute("addressBookEmpty", Boolean.FALSE);270 Mockito.verify(page).addAttribute("isDefaultAddress", Boolean.FALSE);271 assertEquals(FULL_VIEW_PATH, addAddressPage);272 }273 @Test274 public void shouldNotCreateInvalidAddress() throws CMSItemNotFoundException275 {276 BDDMockito.given(Boolean.valueOf(bindingResult.hasErrors())).willReturn(Boolean.TRUE);277 final String addAddressPage = accountController.addAddress(addressForm, bindingResult, page, redirectModel);278 Mockito.verify(accountController).setUpAddressFormAfterError(addressForm, page);279 assertEquals(FULL_VIEW_PATH, addAddressPage);280 }281 @Test282 public void shouldSuggestValidAddress() throws CMSItemNotFoundException283 {284 final AddressVerificationResult<AddressVerificationDecision> avsResult = new AddressVerificationResult<AddressVerificationDecision>();285 avsResult.setDecision(AddressVerificationDecision.REVIEW);286 createBasicAddressFields();287 BDDMockito.given(addressVerificationFacade.verifyAddressData(Mockito.any(AddressData.class))).willReturn(avsResult);288 BDDMockito.given(Boolean.valueOf(289 addressVerificationResultHandler.handleResult(Mockito.eq(avsResult), Mockito.any(AddressData.class), Mockito.eq(page),290 Mockito.eq(redirectModel), Mockito.eq(bindingResult), Mockito.anyBoolean(), Mockito.anyString())))291 .willReturn(Boolean.TRUE);292 final String addAddressPage = accountController.addAddress(addressForm, bindingResult, page, redirectModel);293 assertEquals(FULL_VIEW_PATH, addAddressPage);294 }295 @Test296 public void shouldCreateValidAddress() throws CMSItemNotFoundException297 {298 final AddressVerificationResult<AddressVerificationDecision> avsResult = new AddressVerificationResult<AddressVerificationDecision>();299 avsResult.setDecision(AddressVerificationDecision.ACCEPT);300 createBasicAddressFields();301 BDDMockito.given(addressVerificationFacade.verifyAddressData(Mockito.any(AddressData.class))).willReturn(avsResult);302 BDDMockito.given(Boolean.valueOf(303 addressVerificationResultHandler.handleResult(Mockito.eq(avsResult), Mockito.any(AddressData.class), Mockito.eq(page),304 Mockito.eq(redirectModel), Mockito.eq(bindingResult), Mockito.anyBoolean(), Mockito.anyString())))305 .willReturn(Boolean.FALSE);306 final String addAddressPage = accountController.addAddress(addressForm, bindingResult, page, redirectModel);307 Mockito.verify(userFacade).addAddress(Mockito.any(AddressData.class));308 assertThat(addAddressPage, CoreMatchers.containsString(REDIRECT_TO_EDIT_ADDRESS_PAGE));309 }310 @Test311 public void shouldGetEditAddress() throws CMSItemNotFoundException312 {313 final String addressBookPage = accountController.editAddress(TEST_CODE, page);314 Mockito.verify(page).addAttribute("countryData", checkoutFacade.getDeliveryCountries());315 Mockito.verify(page).addAttribute("titleData", userFacade.getTitles());316 Mockito.verify(page).addAttribute("addressBookEmpty",317 Boolean.valueOf(CollectionUtils.isEmpty(userFacade.getAddressBook())));318 Mockito.verify(page).addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS,319 ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW);320 Mockito.verify(page).addAttribute("edit", Boolean.TRUE);321 assertEquals(FULL_VIEW_PATH, addressBookPage);322 }323 @Test324 public void shouldNotUpdateInvalidAddress() throws CMSItemNotFoundException325 {326 BDDMockito.given(Boolean.valueOf(bindingResult.hasErrors())).willReturn(Boolean.TRUE);327 final String addressBookPage = accountController.editAddress(addressForm, bindingResult, page, redirectModel);328 Mockito.verify(accountController).setUpAddressFormAfterError(addressForm, page);329 assertEquals(FULL_VIEW_PATH, addressBookPage);330 }331 @Test332 public void shouldSuggestValidUpdateAddress() throws CMSItemNotFoundException333 {334 final AddressVerificationResult<AddressVerificationDecision> avsResult = new AddressVerificationResult<AddressVerificationDecision>();335 avsResult.setDecision(AddressVerificationDecision.REVIEW);336 createBasicAddressFields();337 BDDMockito.given(addressVerificationFacade.verifyAddressData(Mockito.any(AddressData.class))).willReturn(avsResult);338 BDDMockito.given(Boolean.valueOf(339 addressVerificationResultHandler.handleResult(Mockito.eq(avsResult), Mockito.any(AddressData.class), Mockito.eq(page),340 Mockito.eq(redirectModel), Mockito.eq(bindingResult), Mockito.anyBoolean(), Mockito.anyString())))341 .willReturn(Boolean.TRUE);342 final String addAddressPage = accountController.editAddress(addressForm, bindingResult, page, redirectModel);343 assertEquals(FULL_VIEW_PATH, addAddressPage);344 }345 @Test346 public void shouldUpdateValidAddress() throws CMSItemNotFoundException347 {348 final String editAddressPage = accountController.editAddress(addressForm, bindingResult, page, redirectModel);349 Mockito.verify(userFacade).editAddress(Mockito.any(AddressData.class));350 assertThat(editAddressPage, CoreMatchers.containsString(REDIRECT_TO_EDIT_ADDRESS_PAGE));351 }352 @Test353 public void shouldSetDefaultAddress()354 {355 final String addressBookPage = accountController.setDefaultAddress(TEST_CODE, redirectModel);356 Mockito.verify(userFacade).setDefaultAddress(Mockito.any(AddressData.class));357 assertEquals(REDIRECT_TO_ADDRESS_BOOK_PAGE, addressBookPage);358 }359 @Test360 public void shouldRemoveAddress()361 {362 final String addressBookPage = accountController.removeAddress(TEST_CODE, redirectModel);363 Mockito.verify(userFacade).removeAddress(Mockito.any(AddressData.class));364 assertEquals(REDIRECT_TO_ADDRESS_BOOK_PAGE, addressBookPage);365 }366 // Orders Tests367 @Test368 public void shouldGetAllOrders() throws CMSItemNotFoundException369 {370 final ShowMode showMode = ShowMode.All;371 setupExistingOrder();372 BDDMockito.given(orderFacade.getPagedOrderHistoryForStatuses(Mockito.any(PageableData.class))).willReturn(searchList);373 final String orderHistoryPage = accountController.orders(1, showMode, "desc", page);374 Mockito.verify(orderFacade).getPagedOrderHistoryForStatuses(Mockito.any(PageableData.class));375 assertEquals(FULL_VIEW_PATH, orderHistoryPage);376 }377 @Test378 public void shouldNotGetNonExistingOrder() throws CMSItemNotFoundException379 {380 BDDMockito.given(orderFacade.getOrderDetailsForCode(TEST_CODE)).willThrow(UnknownIdentifierException.class);381 final String orderHistoryPage = accountController.order(TEST_CODE, page, redirectModel);382 BDDMockito.verify(page, BDDMockito.times(0)).addAttribute(Mockito.anyString(), Mockito.anyString());383 assertEquals(REDIRECT_TO_ORDER_HISTORY_PAGE, orderHistoryPage);384 }385 @Test386 public void shouldGetExistingOrder() throws CMSItemNotFoundException387 {388 setupExistingOrder();389 BDDMockito.given(orderFacade.getOrderDetailsForCode(TEST_CODE)).willReturn(orderData);390 final String myAccountPage = accountController.order(TEST_CODE, page, redirectModel);391 BDDMockito.verify(page, BDDMockito.times(6)).addAttribute(Mockito.anyString(), Mockito.anyString());392 assertEquals(FULL_VIEW_PATH, myAccountPage);393 }394 // Profile Tests395 @Test396 public void shouldGetProfile() throws CMSItemNotFoundException397 {398 final String updateProfilePage = accountController.profile(page);399 BDDMockito.verify(page, BDDMockito.times(7)).addAttribute(Mockito.anyString(), Mockito.anyString());400 assertEquals(FULL_VIEW_PATH, updateProfilePage);401 }402 @Test403 public void shouldGetUpdateProfile() throws CMSItemNotFoundException404 {405 final String profilePage = accountController.editProfile(page);406 BDDMockito.verify(page, BDDMockito.times(7)).addAttribute(Mockito.anyString(), Mockito.anyString());407 assertEquals(FULL_VIEW_PATH, profilePage);408 }409 @Test410 public void shouldNotUpdateProfile() throws CMSItemNotFoundException, DuplicateUidException411 {412 BDDMockito.given(Boolean.valueOf(bindingResult.hasErrors())).willReturn(Boolean.TRUE);413 final String profilePage = accountController.updateProfile(profileForm, bindingResult, page, redirectModel);414 BDDMockito.verify(customerFacade, BDDMockito.times(0)).updateProfile(Mockito.any(CustomerData.class));415 BDDMockito.verify(accountController).setErrorMessagesAndCMSPage(page, UPDATE_PROFILE_CMS_PAGE);416 assertEquals(FULL_VIEW_PATH, profilePage);417 }418 @Test419 public void shouldNotUpdateDuplicateUidProfile() throws CMSItemNotFoundException, DuplicateUidException420 {421 BDDMockito.doThrow(new DuplicateUidException()).when(customerFacade).updateProfile(Mockito.any(CustomerData.class));422 final String profilePage = accountController.updateProfile(profileForm, bindingResult, page, redirectModel);423 BDDMockito.verify(customerFacade).updateProfile(Mockito.any(CustomerData.class));424 BDDMockito.verify(accountController).setErrorMessagesAndCMSPage(page, UPDATE_PROFILE_CMS_PAGE);425 assertEquals(FULL_VIEW_PATH, profilePage);426 }427 @Test428 public void shouldUpdateProfile() throws CMSItemNotFoundException, DuplicateUidException429 {430 final String profilePage = accountController.updateProfile(profileForm, bindingResult, page, redirectModel);431 BDDMockito.verify(customerFacade).updateProfile(Mockito.any(CustomerData.class));432 assertEquals(REDIRECT_TO_UPDATE_PROFILE, profilePage);433 }434 // E-mail Tests435 @Test436 public void shouldGetEmail() throws CMSItemNotFoundException437 {438 final String emailPage = accountController.editEmail(page);439 BDDMockito.verify(page, BDDMockito.times(6)).addAttribute(Mockito.anyString(), Mockito.anyString());440 assertEquals(FULL_VIEW_PATH, emailPage);441 }442 @Test443 public void shouldNotUpdateInavlidEmail() throws CMSItemNotFoundException444 {445 BDDMockito.given(Boolean.valueOf(bindingResult.hasErrors())).willReturn(Boolean.TRUE);446 final String emailUpdatePage = accountController.updateEmail(emailForm, bindingResult, page, redirectModel);447 BDDMockito.verify(accountController).setErrorMessagesAndCMSPage(page, UPDATE_EMAIL_CMS_PAGE);448 assertEquals(FULL_VIEW_PATH, emailUpdatePage);449 }450 @Test451 public void shouldNotUpdateDuplicateEmail() throws CMSItemNotFoundException, PasswordMismatchException, DuplicateUidException452 {453 createEmailForm(EMAIL, FIRST_NAME);454 BDDMockito.doThrow(new DuplicateUidException()).when(customerFacade).changeUid(Mockito.anyString(), Mockito.anyString());455 final String emailUpdatePage = accountController.updateEmail(emailForm, bindingResult, page, redirectModel);456 BDDMockito.verify(bindingResult).rejectValue("email", "profile.email.unique");457 BDDMockito.verify(accountController).setErrorMessagesAndCMSPage(page, UPDATE_EMAIL_CMS_PAGE);458 assertEquals(FULL_VIEW_PATH, emailUpdatePage);459 }460 @Test461 public void shouldNotUpdateInvalidPassword() throws CMSItemNotFoundException, PasswordMismatchException, DuplicateUidException462 {463 createEmailForm(EMAIL, "123");464 BDDMockito.doThrow(new PasswordMismatchException("error")).when(customerFacade).changeUid(Mockito.anyString(),465 Mockito.anyString());466 final String emailUpdatePage = accountController.updateEmail(emailForm, bindingResult, page, redirectModel);467 BDDMockito.verify(bindingResult).rejectValue("password", "profile.currentPassword.invalid");468 BDDMockito.verify(accountController).setErrorMessagesAndCMSPage(page, UPDATE_EMAIL_CMS_PAGE);469 assertEquals(FULL_VIEW_PATH, emailUpdatePage);470 }471 // Password Tests472 @Test473 public void shouldGetPassword() throws CMSItemNotFoundException474 {475 final String passwordPage = accountController.updatePassword(page);476 BDDMockito.verify(page).addAttribute(BDDMockito.eq("updatePasswordForm"), Mockito.any(UpdatePasswordForm.class));477 assertEquals(FULL_VIEW_PATH, passwordPage);478 }479 @Test480 public void shouldNotUpdatePassword() throws CMSItemNotFoundException481 {482 BDDMockito.given(Boolean.valueOf(bindingResult.hasErrors())).willReturn(Boolean.TRUE);483 BDDMockito.given(accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile.updatePasswordForm"))484 .willReturn(breadcrumbsList);485 final String passwordPage = accountController.updatePassword(passwordForm, bindingResult, page, redirectModel);486 BDDMockito.verify(page).addAttribute("breadcrumbs", breadcrumbsList);487 assertEquals(FULL_VIEW_PATH, passwordPage);488 }489 @Test490 public void shouldNotUpdatePasswordNotEqual() throws CMSItemNotFoundException491 {492 BDDMockito.given(passwordForm.getCurrentPassword()).willReturn(TEST_CODE);493 BDDMockito.given(passwordForm.getNewPassword()).willReturn("Different");494 final String passwordPage = accountController.updatePassword(passwordForm, bindingResult, page, redirectModel);495 BDDMockito.verify(bindingResult).rejectValue("checkNewPassword", "validation.checkPwd.equals", new Object[] {},496 "validation.checkPwd.equals");497 assertEquals(REDIRECT_TO_PASSWORD_UPDATE_PAGE, passwordPage);498 }499 @Test500 public void shouldNotUpdatePasswordNotValid() throws CMSItemNotFoundException501 {502 BDDMockito.given(passwordForm.getCheckNewPassword()).willReturn(TEST_CODE);503 BDDMockito.given(passwordForm.getNewPassword()).willReturn(TEST_CODE);504 Mockito.doThrow(new PasswordMismatchException("error")).when(customerFacade).changePassword(Mockito.anyString(),505 Mockito.anyString());506 final String passwordPage = accountController.updatePassword(passwordForm, bindingResult, page, redirectModel);507 BDDMockito.verify(bindingResult).rejectValue("currentPassword", "profile.currentPassword.invalid", new Object[] {},508 "profile.currentPassword.invalid");509 assertEquals(REDIRECT_TO_PASSWORD_UPDATE_PAGE, passwordPage);510 }511 @Test512 public void shouldUpdatePassword() throws CMSItemNotFoundException513 {514 BDDMockito.given(passwordForm.getCheckNewPassword()).willReturn(TEST_CODE);515 BDDMockito.given(passwordForm.getNewPassword()).willReturn(TEST_CODE);516 BDDMockito.given(passwordForm.getCurrentPassword()).willReturn(TEST_CODE);517 final String passwordPage = accountController.updatePassword(passwordForm, bindingResult, page, redirectModel);518 BDDMockito.verify(customerFacade).changePassword(TEST_CODE, TEST_CODE);519 assertEquals(REDIRECT_TO_PASSWORD_UPDATE_PAGE, passwordPage);520 }521 // Payment Tests522 @Test523 public void shouldGetPaymentDetails() throws CMSItemNotFoundException524 {525 final String paymentDetailsPage = accountController.paymentDetails(page);526 BDDMockito.verify(page, BDDMockito.times(7)).addAttribute(Mockito.anyString(), Mockito.anyString());527 assertEquals(FULL_VIEW_PATH, paymentDetailsPage);528 }529 @Test530 public void shouldSetDefaultPaymentDetailsNull() throws CMSItemNotFoundException...
Source:CSRFHandlerInterceptorTest.java
...46 }47 @Test48 public void shouldNotCheckWithNonPostRequest() throws Exception49 {50 BDDMockito.given(request.getMethod()).willReturn("GET");51 boolean verified = csrfHandlerInterceptor.preHandle(request, response, null);52 Assert.assertEquals(true, verified);53 BDDMockito.given(request.getMethod()).willReturn("PUT");54 verified = csrfHandlerInterceptor.preHandle(request, response, null);55 Assert.assertEquals(true, verified);56 BDDMockito.given(request.getMethod()).willReturn("DELETE");57 verified = csrfHandlerInterceptor.preHandle(request, response, null);58 Assert.assertEquals(true, verified);59 }60 @Test61 public void shouldCheckWithPostRequest() throws Exception62 {63 final HttpSession session = Mockito.mock(HttpSession.class);64 BDDMockito.given(session.getAttribute(SESSION_CSRF_ATTRIBUTE)).willReturn("123");65 BDDMockito.given(request.getMethod()).willReturn("POST");66 BDDMockito.given(request.getSession()).willReturn(session);67 BDDMockito.given(request.getParameter(CSRFTokenManager.CSRF_PARAM_NAME)).willReturn("123");68 final boolean verified = csrfHandlerInterceptor.preHandle(request, response, null);69 Assert.assertEquals(true, verified);70 }71 @Test72 public void shouldErrorOnMismatchTokens() throws Exception73 {74 final HttpSession session = Mockito.mock(HttpSession.class);75 BDDMockito.given(session.getAttribute(SESSION_CSRF_ATTRIBUTE)).willReturn("1234");76 BDDMockito.given(request.getMethod()).willReturn("POST");77 BDDMockito.given(request.getSession()).willReturn(session);78 BDDMockito.given(request.getParameter(CSRFTokenManager.CSRF_PARAM_NAME)).willReturn("123");79 final boolean verified = csrfHandlerInterceptor.preHandle(request, response, null);80 verify(response, times(1)).sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");81 Assert.assertEquals(false, verified);82 }83 @Test84 public void shouldPassOnExemptUrl() throws Exception85 {86 final String originalValues = Config.getParameter(CSRF_URL_PROPERTY);87 try88 {89 Config.setParameter(CSRF_URL_PROPERTY, "/[^/]+(/[^?]*)+(sop-response)$");90 final HttpSession session = Mockito.mock(HttpSession.class);91 BDDMockito.given(session.getAttribute(SESSION_CSRF_ATTRIBUTE)).willReturn("1234");92 // Mismatch tokens93 BDDMockito.given(request.getParameter(CSRFTokenManager.CSRF_PARAM_NAME)).willReturn("123");94 BDDMockito.given(request.getMethod()).willReturn("POST");95 BDDMockito.given(request.getSession()).willReturn(session);96 BDDMockito.given(request.getServletPath()).willReturn("/checkout/multi/sop-response");97 final boolean verified = csrfHandlerInterceptor.preHandle(request, response, null);98 Assert.assertEquals(true, verified);99 }100 finally101 {102 Config.setParameter(CSRF_URL_PROPERTY, originalValues);103 }104 }105}...
willReturn
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.InjectMocks;4import org.mockito.Mock;5import org.mockito.Mockito;6import org.mockito.junit.MockitoJUnitRunner;7import static org.mockito.BDDMockito.*;8@RunWith(MockitoJUnitRunner.class)9public class MockitoTest {10 private Service service;11 private Client client;12 public void test1() {13 given(service.doStuff()).willReturn("Hello");14 client.doSomething();15 Mockito.verify(service).doStuff();16 }17}18service.doStuff();19-> at Client.doSomething(MockitoTest.java:19)20at org.mockito.internal.verification.VerificationModeFactory$1.findMissingInvocation(VerificationModeFactory.java:90)21at org.mockito.internal.verification.VerificationModeFactory$1.verify(VerificationModeFactory.java:64)22at org.mockito.internal.verification.VerificationModeFactory$1.verify(VerificationModeFactory.java:52)23at org.mockito.internal.invocation.InvocationMatcher$1.answer(InvocationMatcher.java:34)24at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:93)25at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)26at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)27at org.mockito.internal.creation.cglib.MethodInterceptorFilter.intercept(MethodInterceptorF
willReturn
Using AI Code Generation
1public class MockitoTest {2 public void test() {3 List mockedList = mock(List.class);4 given(mockedList.get(0)).willReturn("first");5 assertEquals("first", mockedList.get(0));6 assertEquals(null, mockedList.get(1));7 }8}9public class MockitoTest {10 public void test() {11 List mockedList = mock(List.class);12 given(mockedList.get(anyInt())).willReturn("element");13 assertEquals("element", mockedList.get(999));14 }15}16public class MockitoTest {17 public void test() {18 List mockedList = mock(List.class);19 given(mockedList.get(anyInt())).willAnswer(new Answer<String>() {20 public String answer(InvocationOnMock invocation) {21 Object[] args = invocation.getArguments();22 Object mock = invocation.getMock();23 return "called with arguments: " + args;24 }25 });26 assertEquals("called with arguments: [0]", mockedList.get(0));27 }28}29public class MockitoTest {30 public void test() {31 List mockedList = mock(List.class);32 given(mockedList.get(anyInt())).willThrow(new RuntimeException());33 mockedList.get(999);34 }35}36public class MockitoTest {37 public void test() {38 List mockedList = mock(List.class);39 willDoNothing().given(mockedList).clear();40 mockedList.clear();41 }42}43public class MockitoTest {44 public void test() {45 List mockedList = mock(List.class);46 willDoNothing().given(mockedList).clear();47 willThrow(new RuntimeException()).given(mockedList).clear();48 mockedList.clear();49 }50}
willReturn
Using AI Code Generation
1package com.ack.junit.mock;2import org.junit.Test;3import org.mockito.BDDMockito;4import org.mockito.Mockito;5import java.util.Iterator;6import java.util.List;7import static org.junit.Assert.assertEquals;8import static org.mockito.BDDMockito.given;9import static org.mockito.BDDMockito.then;10public class BDDMockitoTest {11 public void testIteratorWontNext() {12 Iterator<String> iterator = Mockito.mock( Iterator.class );13 given( iterator.next() ).willReturn( "Hello" ).willReturn( "World" );14 String result = iterator.next() + " " + iterator.next();15 assertEquals( "Hello World", result );16 }17 public void testIteratorWontNext2() {18 Iterator<String> iterator = Mockito.mock( Iterator.class );19 BDDMockito.given( iterator.next() ).willReturn( "Hello" ).willReturn( "World" );20 String result = iterator.next() + " " + iterator.next();21 assertEquals( "Hello World", result );22 }23 public void testWithBDDMockito() {24 List<String> list = Mockito.mock( List.class );25 BDDMockito.given( list.get( 0 ) ).willReturn( "Hello" );26 String result = list.get( 0 );27 assertEquals( "Hello", result );28 }29 public void testWithBDDMockito2() {30 List<String> list = Mockito.mock( List.class );31 given( list.get( 0 ) ).willReturn( "Hello" );32 String result = list.get( 0 );33 assertEquals( "Hello", result );34 }35 public void testWithBDDMockito3() {36 List<String> list = Mockito.mock( List.class );37 BDDMockito.given( list.get( 0 ) ).willReturn( "Hello" );38 String result = list.get( 0 );39 assertEquals( "Hello", result );40 then( list ).should().get( 0 );41 }
willReturn
Using AI Code Generation
1import static org.mockito.BDDMockito.*;2import java.util.List;3import org.junit.Test;4public class MockitoBDDTest {5public void test() {6List<String> mockList = mock(List.class);7given(mockList.get(0)).willReturn("Mockito");8String result = mockList.get(0);9assert result.equals("Mockito");10}11}12import static org.mockito.Mockito.*;13import java.util.List;14import org.junit.Test;15public class MockitoBDDTest {16public void test() {17List<String> mockList = mock(List.class);18when(mockList.get(0)).thenReturn("Mockito");19String result = mockList.get(0);20assert result.equals("Mockito");21}22}
willReturn
Using AI Code Generation
1import static org.mockito.BDDMockito.*;2class Simple{3public int add(int a, int b){4return a+b;5}6}7public class MockitoTest{8public static void main(String[] args){9Simple s = mock(Simple.class);10given(s.add(2,3)).willReturn(5);11System.out.println(s.add(2,3));12}13}14The willReturn() method of the org.mockito.BDDMockito class is used to return the value that we want to test. It takes the value that we want to
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!!