Best Mockito code snippet using org.mockito.ArgumentMatchers.anyVararg
Source:FormControllerTest.java
...11import static org.mockito.ArgumentMatchers.any;12import static org.mockito.ArgumentMatchers.anyBoolean;13import static org.mockito.ArgumentMatchers.anyInt;14import static org.mockito.ArgumentMatchers.anyString;15import static org.mockito.ArgumentMatchers.anyVararg;16import static org.mockito.Mockito.doNothing;17import static org.mockito.Mockito.times;18import static org.mockito.Mockito.verify;19import static org.mockito.Mockito.verifyNoMoreInteractions;20import static org.mockito.Mockito.when;21import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;22import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;23import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;24import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;25import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;26import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;27import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;28import java.util.ArrayList;29import java.util.Arrays;30import java.util.List;31import org.hamcrest.Matchers;32import org.junit.Before;33import org.junit.Test;34import org.junit.runner.RunWith;35import org.mockito.InjectMocks;36import org.mockito.Mock;37import org.mockito.MockitoAnnotations;38import org.mockito.junit.MockitoJUnitRunner;39import org.springframework.http.MediaType;40import org.springframework.test.web.servlet.MockMvc;41import org.springframework.test.web.servlet.RequestBuilder;42import org.springframework.test.web.servlet.ResultActions;43import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;44import org.springframework.test.web.servlet.result.MockMvcResultHandlers;45import org.springframework.test.web.servlet.result.MockMvcResultMatchers;46import org.springframework.test.web.servlet.setup.MockMvcBuilders;47import com.ihsinformatics.coronavirus.BaseTestData;48import com.ihsinformatics.coronavirus.dto.FormDataDesearlizeDto;49import com.ihsinformatics.coronavirus.model.BaseEntity;50import com.ihsinformatics.coronavirus.model.FormData;51import com.ihsinformatics.coronavirus.model.FormType;52import com.ihsinformatics.coronavirus.model.Location;53import com.ihsinformatics.coronavirus.model.Participant;54import com.ihsinformatics.coronavirus.service.DonorService;55import com.ihsinformatics.coronavirus.service.FormService;56import com.ihsinformatics.coronavirus.service.LocationService;57import com.ihsinformatics.coronavirus.service.MetadataService;58import com.ihsinformatics.coronavirus.service.ParticipantService;59import com.ihsinformatics.coronavirus.service.UserService;60import com.ihsinformatics.coronavirus.util.DateTimeUtil;61import com.ihsinformatics.coronavirus.web.FormController;62/**63 * @author owais.hussain@ihsinformatics.com64 */65@RunWith(MockitoJUnitRunner.class)66public class FormControllerTest extends BaseTestData {67 private static String API_PREFIX = "/api/";68 private MockMvc mockMvc;69 @Mock70 private FormService formService;71 @Mock72 private LocationService locationService;73 74 @Mock75 private ParticipantService participantService;76 77 @Mock78 private MetadataService metadataService;79 80 @Mock81 private UserService userService;82 83 @Mock84 private DonorService donorService;85 86 @InjectMocks87 private FormController formController;88 private FormData quidditch95, quidditch98, drinkingChallenge, reverseFlightTraining;89 @Before90 public void reset() {91 super.initData();92 MockitoAnnotations.initMocks(this);93 mockMvc = MockMvcBuilders.standaloneSetup(formController).alwaysDo(MockMvcResultHandlers.print()).build();94 List<Participant> participants = new ArrayList<>();95 participants.add(seeker);96 participants.add(keeper);97 quidditch95 = FormData.builder().formType(quidditchForm).location(hogwartz)98 .formDate(DateTimeUtil.create(15, 1, 1995)).referenceId("1995").formParticipants(participants).build();99 participants.add(chaser);100 quidditch98 = FormData.builder().formType(quidditchForm).location(hogwartz)101 .formDate(DateTimeUtil.create(1, 2, 1998)).referenceId("1998").formParticipants(participants).build();102 drinkingChallenge = FormData.builder().formType(challengeForm).location(diagonalley)103 .formDate(DateTimeUtil.create(20, 6, 1995)).referenceId("DALLEY_CH_24").build();104 reverseFlightTraining = FormData.builder().formType(trainingForm).location(diagonalley)105 .formDate(DateTimeUtil.create(1, 2, 1998)).referenceId("DALLEY_TR_144").formParticipants(participants)106 .build();107 }108 /**109 * Test method for110 * {@link com.ihsinformatics.coronavirus.web.FormController#createFormData(com.ihsinformatics.coronavirus.model.FormData)}.111 * 112 * @throws Exception113 */114 @Test115 public void shouldCreateFormData() throws Exception {116 when(formService.saveFormData(any(FormData.class))).thenReturn(quidditch95);117 String content = BaseEntity.getGson().toJson(quidditch95);118 RequestBuilder requestBuilder = MockMvcRequestBuilders.post(API_PREFIX + "formdata")119 .accept(MediaType.APPLICATION_JSON_UTF8).contentType(MediaType.APPLICATION_JSON_UTF8).content(content);120 ResultActions actions = mockMvc.perform(requestBuilder);121 actions.andExpect(status().isCreated());122 String expectedUrl = API_PREFIX + "formdata/" + quidditch95.getUuid();123 actions.andExpect(MockMvcResultMatchers.redirectedUrl(expectedUrl));124 verify(formService, times(1)).saveFormData(any(FormData.class));125 }126 /**127 * Test method for128 * {@link com.ihsinformatics.coronavirus.web.FormController#createFormType(com.ihsinformatics.coronavirus.model.FormType)}.129 * 130 * @throws Exception131 */132 @Test133 public void shouldCreateFormType() throws Exception {134 when(formService.saveFormType(any(FormType.class))).thenReturn(quidditchForm);135 String content = BaseEntity.getGson().toJson(quidditchForm);136 RequestBuilder requestBuilder = MockMvcRequestBuilders.post(API_PREFIX + "formtype")137 .accept(MediaType.APPLICATION_JSON_UTF8).contentType(MediaType.APPLICATION_JSON_UTF8).content(content);138 ResultActions actions = mockMvc.perform(requestBuilder);139 actions.andExpect(status().isCreated());140 String expectedUrl = API_PREFIX + "formtype/" + quidditchForm.getUuid();141 actions.andExpect(MockMvcResultMatchers.redirectedUrl(expectedUrl));142 verify(formService, times(1)).saveFormType(any(FormType.class));143 }144 @Test145 public void shouldCreateReferenceId() throws Exception {146 dumbledore.setUserId(100);147 hogwartz.setLocationId(100);148 String referenceId = formController.createReferenceId(dumbledore, hogwartz, quidditch95.getFormDate());149 assertEquals("100-100-" + DateTimeUtil.toString(quidditch95.getFormDate(), DateTimeUtil.SQL_TIMESTAMP),150 referenceId);151 }152 /**153 * Test method for154 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormData(java.lang.String)}.155 * 156 * @throws Exception157 */158 @Test159 public void shouldGetFormData() throws Exception {160 when(formService.getFormDataByUuid(any(String.class))).thenReturn(quidditch95);161 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/{uuid}", quidditch95.getUuid()));162 actions.andExpect(status().isOk());163 actions.andExpect(jsonPath("$.uuid", Matchers.is(quidditch95.getUuid())));164 verify(formService, times(1)).getFormDataByUuid(any(String.class));165 }166 /**167 * Test method for168 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormDataByDateRange(java.util.Date, java.util.Date, java.lang.Integer, java.lang.Integer)}.169 * 170 * @throws Exception171 */172 @Test173 @SuppressWarnings("deprecation")174 public void shouldGetFormDataByDatePaging() throws Exception {175 when(formService.getFormDataByDate(anyVararg(), anyVararg(), anyInt(), anyInt(), anyString(), anyBoolean()))176 .thenReturn(Arrays.asList(reverseFlightTraining, quidditch98));177 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/date")178 .param("from", DateTimeUtil.toSqlDateString(DateTimeUtil.create(1, 1, 1998)))179 .param("to", DateTimeUtil.toSqlDateString(DateTimeUtil.create(31, 12, 1998))).param("page", "1")180 .param("size", "10"));181 actions.andExpect(status().isOk());182 actions.andExpect(jsonPath("$", Matchers.hasSize(2)));183 verify(formService, times(1)).getFormDataByDate(anyVararg(), anyVararg(), anyInt(), anyInt(), anyString(),184 anyBoolean());185 }186 187 /**188 * Test method for189 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormDataByDateRange(java.util.Date, java.util.Date, java.lang.Integer, java.lang.Integer)}.190 * 191 * @throws Exception192 */193 @Test194 @SuppressWarnings("deprecation")195 public void shouldGetFormDataByDate() throws Exception {196 when(formService.getFormDataByDate(anyVararg(), anyVararg()))197 .thenReturn(Arrays.asList(reverseFlightTraining, quidditch98));198 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/list/date")199 .param("from", DateTimeUtil.toSqlDateString(DateTimeUtil.create(1, 1, 1998)))200 .param("to", DateTimeUtil.toSqlDateString(DateTimeUtil.create(31, 12, 1998))));201 actions.andExpect(status().isOk());202 actions.andExpect(jsonPath("$", Matchers.hasSize(2)));203 verify(formService, times(1)).getFormDataByDate(anyVararg(), anyVararg());204 }205 /**206 * Test method for207 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormData(java.lang.String)}.208 * 209 * @throws Exception210 */211 @Test212 public void shouldGetFormDataById() throws Exception {213 when(formService.getFormDataById(any(Integer.class))).thenReturn(quidditch95);214 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/id/{id}", 1));215 actions.andExpect(status().isOk());216 actions.andExpect(jsonPath("$.uuid", Matchers.is(quidditch95.getUuid())));217 verify(formService, times(1)).getFormDataById(any(Integer.class));218 }219 /**220 * Test method for221 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormDataByLocation(java.lang.String)}.222 * 223 * @throws Exception224 */225 @Test226 public void shouldGetFormDataByLocation() throws Exception {227 when(locationService.getLocationByUuid(any(String.class))).thenReturn(hogwartz);228 when(formService.getFormDataByLocation(any(Location.class)))229 .thenReturn(Arrays.asList(quidditch95, quidditch98));230 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/location/{uuid}", hogwartz.getUuid()));231 actions.andExpect(status().isOk());232 actions.andExpect(jsonPath("$", Matchers.hasSize(2)));233 verify(locationService, times(1)).getLocationByUuid(any(String.class));234 verify(formService, times(1)).getFormDataByLocation(any(Location.class));235 }236 /**237 * Test method for238 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormDataByLocation(java.lang.String)}.239 * 240 * @throws Exception241 */242 @Test243 public void shouldGetFormDataByLocationShortName() throws Exception {244 when(locationService.getLocationByShortName(any(String.class))).thenReturn(hogwartz);245 when(formService.getFormDataByLocation(any(Location.class)))246 .thenReturn(Arrays.asList(quidditch95, quidditch98));247 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/location/{uuid}", hogwartz.getShortName()));248 actions.andExpect(status().isOk());249 actions.andExpect(jsonPath("$", Matchers.hasSize(2)));250 verify(locationService, times(1)).getLocationByShortName(any(String.class));251 verify(formService, times(1)).getFormDataByLocation(any(Location.class));252 }253 /**254 * Test method for255 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormDataByReferenceId(java.lang.String)}.256 * 257 * @throws Exception258 */259 @Test260 public void shouldGetFormDataByReferenceId() throws Exception {261 when(formService.getFormDataByReferenceId(any(String.class))).thenReturn(drinkingChallenge);262 ResultActions actions = mockMvc263 .perform(get(API_PREFIX + "formdata/referenceid/{referenceId}", drinkingChallenge.getReferenceId()));264 actions.andExpect(status().isOk());265 actions.andExpect(jsonPath("$.referenceId", Matchers.is(drinkingChallenge.getReferenceId())));266 verify(formService, times(1)).getFormDataByReferenceId(any(String.class));267 }268 /**269 * Test method for270 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormType(java.lang.String)}.271 * 272 * @throws Exception273 */274 @Test275 public void shouldGetFormType() throws Exception {276 when(formService.getFormTypeByUuid(any(String.class))).thenReturn(quidditchForm);277 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formtype/{uuid}", quidditchForm.getUuid()));278 actions.andExpect(status().isOk());279 actions.andExpect(jsonPath("$.shortName", Matchers.is(quidditchForm.getShortName())));280 verify(formService, times(1)).getFormTypeByUuid(any(String.class));281 }282 /**283 * Test method for284 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormType(java.lang.String)}.285 * 286 * @throws Exception287 */288 @Test289 public void shouldGetFormTypeById() throws Exception {290 when(formService.getFormTypeById(any(Integer.class))).thenReturn(quidditchForm);291 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formtype/id/{id}", 1));292 actions.andExpect(status().isOk());293 actions.andExpect(jsonPath("$.uuid", Matchers.is(quidditchForm.getUuid())));294 verify(formService, times(1)).getFormTypeById(any(Integer.class));295 }296 /**297 * Test method for298 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormTypeByShortName(java.lang.String)}.299 * 300 * @throws Exception301 */302 @Test303 public void shouldGetFormTypeByShortName() throws Exception {304 when(formService.getFormTypeByName(any(String.class))).thenReturn(quidditchForm);305 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formtype/name/{name}", quidditchForm.getShortName()));306 actions.andExpect(status().isOk());307 actions.andExpect(jsonPath("$.shortName", Matchers.is(quidditchForm.getShortName())));308 verify(formService, times(1)).getFormTypeByName(any(String.class));309 }310 /**311 * Test method for312 * {@link com.ihsinformatics.coronavirus.web.FormController#getFormTypes()}.313 * 314 * @throws Exception315 */316 @Test317 public void shouldGetFormTypes() throws Exception {318 when(formService.getAllFormTypes(true)).thenReturn(Arrays.asList(quidditchForm, challengeForm, trainingForm));319 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formtypes"));320 actions.andExpect(status().isOk());321 actions.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));322 actions.andExpect(jsonPath("$", Matchers.hasSize(3)));323 verify(formService, times(1)).getAllFormTypes(true);324 verifyNoMoreInteractions(formService);325 }326 /**327 * Test method for328 * {@link com.ihsinformatics.coronavirus.web.FormController#retireFormType(java.lang.String)}.329 * 330 * @throws Exception331 */332 @Test333 public void shouldRetireFormType() throws Exception {334 when(formService.getFormTypeByUuid(any(String.class))).thenReturn(challengeForm);335 doNothing().when(formService).retireFormType(challengeForm);336 ResultActions actions = mockMvc.perform(delete(API_PREFIX + "formtype/{uuid}", challengeForm.getUuid()));337 actions.andExpect(status().isNoContent());338 verify(formService, times(1)).getFormTypeByUuid(challengeForm.getUuid());339 verify(formService, times(1)).retireFormType(challengeForm);340 verifyNoMoreInteractions(formService);341 }342 /**343 * Test method for344 * {@link com.ihsinformatics.coronavirus.web.FormController#searchFormData(com.ihsinformatics.coronavirus.model.FormType, com.ihsinformatics.coronavirus.model.Location, java.util.Date, java.util.Date, java.lang.Integer, java.lang.Integer)}.345 * 346 * @throws Exception347 */348 @SuppressWarnings("deprecation")349 @Test350 public void shouldSearchFormData() throws Exception {351 when(formService.getFormTypeByUuid(anyString())).thenReturn(quidditchForm);352 when(locationService.getLocationByUuid(anyString())).thenReturn(hogwartz);353 when(formService.searchFormData(anyVararg(), anyVararg(), anyVararg(), anyVararg(), anyInt(), anyInt(),354 anyString(), anyBoolean())).thenReturn(Arrays.asList(quidditch95, quidditch98));355 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/search")356 .param("formType", quidditchForm.getUuid()).param("location", hogwartz.getUuid())357 .param("from", DateTimeUtil.toSqlDateString(DateTimeUtil.create(1, 1, 1995)))358 .param("to", DateTimeUtil.toSqlDateString(DateTimeUtil.create(31, 12, 1998))).param("page", "1")359 .param("size", "10"));360 actions.andExpect(status().isOk());361 actions.andExpect(jsonPath("$", Matchers.hasSize(2)));362 verify(formService, times(1)).getFormTypeByUuid(anyString());363 verify(locationService, times(1)).getLocationByUuid(anyString());364 verify(formService, times(1)).searchFormData(anyVararg(), anyVararg(), anyVararg(), anyVararg(), anyInt(),365 anyInt(), anyString(), anyBoolean());366 }367 /**368 * Test method for369 * {@link com.ihsinformatics.coronavirus.web.FormController#searchFormData(com.ihsinformatics.coronavirus.model.FormType, com.ihsinformatics.coronavirus.model.Location, java.util.Date, java.util.Date, java.lang.Integer, java.lang.Integer)}.370 * 371 * @throws Exception372 */373 @SuppressWarnings("deprecation")374 @Test375 public void shouldSearchFormDataNonPaging() throws Exception {376 when(formService.getFormTypeByUuid(anyString())).thenReturn(quidditchForm);377 when(locationService.getLocationByUuid(anyString())).thenReturn(hogwartz);378 when(formService.searchFormData(anyVararg(), anyVararg(), anyVararg(), anyVararg(), anyVararg(),379 anyString(), anyBoolean())).thenReturn(Arrays.asList(quidditch95, quidditch98));380 ResultActions actions = mockMvc.perform(get(API_PREFIX + "formdata/list/search")381 .param("formType", quidditchForm.getUuid()).param("location", hogwartz.getUuid())382 .param("from", DateTimeUtil.toSqlDateString(DateTimeUtil.create(1, 1, 1995)))383 .param("to", DateTimeUtil.toSqlDateString(DateTimeUtil.create(31, 12, 1998))).param("page", "1")384 .param("size", "10"));385 actions.andExpect(status().isOk());386 actions.andExpect(jsonPath("$", Matchers.hasSize(2)));387 verify(formService, times(1)).getFormTypeByUuid(anyString());388 verify(locationService, times(1)).getLocationByUuid(anyString());389 verify(formService, times(1)).searchFormData(anyVararg(), anyVararg(), anyVararg(), anyVararg(), anyVararg(), anyString(), anyBoolean());390 }391 392 /**393 * Test method for394 * {@link com.ihsinformatics.coronavirus.web.FormController#unretireFormType(java.lang.String)}.395 * 396 * @throws Exception397 */398 @Test399 public void shouldUnretireFormType() throws Exception {400 when(formService.getFormTypeByUuid(any(String.class))).thenReturn(quidditchForm);401 doNothing().when(formService).unretireFormType(quidditchForm);402 ResultActions actions = mockMvc.perform(patch(API_PREFIX + "formtype/{uuid}", quidditchForm.getUuid()));403 actions.andExpect(status().isNoContent());...
Source:UsageOfAnyMatchersInspectionAnyTest.java
...139 }140 public void testAnyVarargIsReplacedWithAnyWithStaticImport() {141 doQuickFixTest("Replace with ArgumentMatchers.any()", "UseAnyInsteadOfAnyVarargStaticImportTest.java",142 "import org.mockito.Mockito;\n" +143 "import static org.mockito.ArgumentMatchers.anyVararg;\n" +144 "\n" +145 "public class UseAnyInsteadOfAnyVarargStaticImportTest {\n" +146 " public void testMethod() {\n" +147 " MockObject mock = Mockito.mock(MockObject.class);\n" +148 " Mockito.doReturn(10).when(mock).method(anyVar<caret>arg());\n" +149 " }\n" +150 " private static final class MockObject {\n" +151 " public int method(String s) {\n" +152 " return 0;\n" +153 " }\n" +154 " }\n" +155 "}",156 "import org.mockito.Mockito;\n" +157 "\n" +158 "import static org.mockito.ArgumentMatchers.any;\n" +159 "import static org.mockito.ArgumentMatchers.anyVararg;\n" +160 "\n" +161 "public class UseAnyInsteadOfAnyVarargStaticImportTest {\n" +162 " public void testMethod() {\n" +163 " MockObject mock = Mockito.mock(MockObject.class);\n" +164 " Mockito.doReturn(10).when(mock).method(any());\n" +165 " }\n" +166 " private static final class MockObject {\n" +167 " public int method(String s) {\n" +168 " return 0;\n" +169 " }\n" +170 " }\n" +171 "}");172 }173 public void testAnyIsNotReported() {...
Source:DefaultRegistrationServiceTest.java
...9 */10package org.jbb.members.impl.registration;11import static org.assertj.core.api.Assertions.assertThat;12import static org.mockito.ArgumentMatchers.any;13import static org.mockito.ArgumentMatchers.anyVararg;14import static org.mockito.ArgumentMatchers.eq;15import static org.mockito.ArgumentMatchers.nullable;16import static org.mockito.BDDMockito.given;17import static org.mockito.Mockito.doThrow;18import static org.mockito.Mockito.mock;19import static org.mockito.Mockito.times;20import static org.mockito.Mockito.verify;21import com.google.common.collect.Sets;22import com.google.common.eventbus.EventBus;23import java.util.Optional;24import javax.validation.ConstraintViolation;25import javax.validation.Validator;26import org.jbb.members.api.registration.RegistrationException;27import org.jbb.members.api.registration.RegistrationMetaData;28import org.jbb.members.api.registration.RegistrationRequest;29import org.jbb.members.event.MemberRegisteredEvent;30import org.jbb.members.impl.base.MembersProperties;31import org.jbb.members.impl.base.dao.MemberRepository;32import org.jbb.members.impl.base.model.MemberEntity;33import org.jbb.members.impl.registration.model.RegistrationMetaDataEntity;34import org.jbb.security.api.password.PasswordException;35import org.junit.Test;36import org.junit.runner.RunWith;37import org.mockito.InjectMocks;38import org.mockito.Mock;39import org.mockito.junit.MockitoJUnitRunner;40import org.springframework.security.core.userdetails.UsernameNotFoundException;41@RunWith(MockitoJUnitRunner.class)42public class DefaultRegistrationServiceTest {43 @Mock44 private MemberRepository memberRepositoryMock;45 @Mock46 private RegistrationMetaDataEntityFactory registrationMetaDataFactoryMock;47 @Mock48 private MemberEntityFactory memberFactoryMock;49 @Mock50 private Validator validatorMock;51 @Mock52 private EventBus eventBusMock;53 @Mock54 private MembersProperties propertiesMock;55 @Mock56 private PasswordSaver passwordSaverMock;57 @InjectMocks58 private DefaultRegistrationService registrationService;59 @Test(expected = NullPointerException.class)60 public void shouldThrowNPE_whenNullRegistrationRequestHandled() {61 // when62 registrationService.register(null);63 // then64 // throw NullPointerException65 }66 @Test67 public void shouldEmitMemberRegistrationEvent_whenRegistrationCompleted() {68 // when69 MemberEntity memberEntityMock = mock(MemberEntity.class);70 given(memberEntityMock.getId()).willReturn(23L);71 given(memberFactoryMock.create(any(), any())).willReturn(memberEntityMock);72 given(memberRepositoryMock.save(any(MemberEntity.class))).willReturn(memberEntityMock);73 registrationService.register(mock(RegistrationRequest.class));74 // then75 verify(eventBusMock, times(1)).post(any(MemberRegisteredEvent.class));76 }77 @Test(expected = RegistrationException.class)78 public void shouldThrowRegistrationException_whenValidationForMemberEntityFailed() {79 // given80 MemberEntity memberEntityMock = mock(MemberEntity.class);81 given(memberEntityMock.getId()).willReturn(23L);82 given(memberFactoryMock.create(any(), any())).willReturn(memberEntityMock);83 given(memberRepositoryMock.save(any(MemberEntity.class))).willReturn(memberEntityMock);84 given(validatorMock.validate(any(), anyVararg()))85 .willReturn(Sets.newHashSet(mock(ConstraintViolation.class)));86 // when87 registrationService.register(mock(RegistrationRequest.class));88 // then89 // throw RegistrationException90 }91 @Test(expected = RegistrationException.class)92 public void shouldThrowRegistrationException_whenValidationOfPasswordFailed() {93 // given94 PasswordException passwordExceptionMock = mock(PasswordException.class);95 given(passwordExceptionMock.getConstraintViolations()).willReturn(Sets.newHashSet(mock(ConstraintViolation.class)));96 doThrow(passwordExceptionMock).when(passwordSaverMock).save(any(), any());97 given(memberRepositoryMock.save(nullable(MemberEntity.class))).willReturn(MemberEntity.builder().build());98 // when...
Source:ParameterizedConstructorInstantiatorTest.java
...62 @Test63 public void should_instantiate_type_if_resolver_provide_matching_types() throws Exception {64 Observer observer = mock(Observer.class);65 Map map = mock(Map.class);66 given(resolver.resolveTypeInstances(ArgumentMatchers.<Class<?>[]>anyVararg()))67 .willReturn(new Object[] {observer, map});68 new ParameterizedConstructorInstantiator(this, field("withMultipleConstructor"), resolver)69 .instantiate();70 assertNotNull(withMultipleConstructor);71 assertNotNull(withMultipleConstructor.observer);72 assertNotNull(withMultipleConstructor.map);73 }74 @Test75 public void should_fail_if_an_argument_instance_type_do_not_match_wanted_type()76 throws Exception {77 Observer observer = mock(Observer.class);78 Set<?> wrongArg = mock(Set.class);79 given(resolver.resolveTypeInstances(ArgumentMatchers.<Class<?>[]>any()))80 .willReturn(new Object[] {observer, wrongArg});81 try {82 new ParameterizedConstructorInstantiator(83 this, field("withMultipleConstructor"), resolver)84 .instantiate();85 fail();86 } catch (MockitoException e) {87 assertThat(e.getMessage()).contains("argResolver").contains("incorrect types");88 }89 }90 @Test91 public void should_report_failure_if_constructor_throws_exception() throws Exception {92 given(resolver.resolveTypeInstances(ArgumentMatchers.<Class<?>[]>anyVararg()))93 .willReturn(new Object[] {null});94 try {95 new ParameterizedConstructorInstantiator(96 this, field("withThrowingConstructor"), resolver)97 .instantiate();98 fail();99 } catch (MockitoException e) {100 assertThat(e.getMessage()).contains("constructor").contains("raised an exception");101 }102 }103 @Test104 public void should_instantiate_type_with_vararg_constructor() throws Exception {105 Observer[] vararg = new Observer[] {};106 given(resolver.resolveTypeInstances(ArgumentMatchers.<Class<?>[]>anyVararg()))107 .willReturn(new Object[] {"", vararg});108 new ParameterizedConstructorInstantiator(this, field("withVarargConstructor"), resolver)109 .instantiate();110 assertNotNull(withVarargConstructor);111 }112 private Field field(String fieldName) throws NoSuchFieldException {113 Field field = this.getClass().getDeclaredField(fieldName);114 field.setAccessible(true);115 return field;116 }117 private static class NoArgConstructor {118 NoArgConstructor() {}119 }120 private static class OneConstructor {...
Source:LienzoImageStripLoaderTest.java
...26import org.kie.workbench.common.stunner.core.util.DefinitionUtils;27import org.mockito.Mock;28import org.uberfire.mvp.Command;29import static org.mockito.ArgumentMatchers.any;30import static org.mockito.ArgumentMatchers.anyVararg;31import static org.mockito.ArgumentMatchers.eq;32import static org.mockito.Mockito.doAnswer;33import static org.mockito.Mockito.mock;34import static org.mockito.Mockito.times;35import static org.mockito.Mockito.verify;36import static org.mockito.Mockito.when;37@RunWith(LienzoMockitoTestRunner.class)38public class LienzoImageStripLoaderTest {39 private static final ImageStrip[] STRIPS = new ImageStrip[0];40 @Mock41 private DefinitionUtils definitionUtils;42 @Mock43 private ImageStripRegistry stripRegistry;44 @Mock45 private LienzoImageStrips lienzoImageStrips;46 @Mock47 private Metadata metadata;48 @Mock49 private Annotation qualifier;50 private LienzoImageStripLoader tested;51 @Before52 public void setUp() {53 doAnswer(invocation -> {54 ((Command) invocation.getArguments()[1]).execute();55 return null;56 }).when(lienzoImageStrips).register(any(ImageStrip[].class),57 any(Command.class));58 when(stripRegistry.get(any(Annotation.class))).thenReturn(STRIPS);59 when(stripRegistry.get((Annotation[]) anyVararg())).thenReturn(STRIPS);60 when(metadata.getDefinitionSetId()).thenReturn("mds1");61 when(definitionUtils.getQualifier(eq("mds1"))).thenReturn(qualifier);62 tested = new LienzoImageStripLoader(definitionUtils,63 stripRegistry,64 lienzoImageStrips);65 }66 @Test67 public void testInit() {68 Command callback = mock(Command.class);69 tested.init(metadata, callback);70 verify(stripRegistry, times(1)).get(eq(DefinitionManager.DEFAULT_QUALIFIER), eq(qualifier));71 verify(lienzoImageStrips, times(1)).register(eq(STRIPS), eq(callback));72 }73 @Test...
Source:GuidesOrgTests.java
...25 MatcherAssert.assertThat(service.getMarkdownFileAsHtml("/path/to/html"), equalTo("<h1>Something</h1>"));26 }27 @Test28 public void getRepoInfo_fetchesGitHubRepos() {29 BDDMockito.given(ghClient.sendRequestForJson(ArgumentMatchers.anyString(), ArgumentMatchers.anyVararg())).willReturn(Fixtures.githubRepoJson());30 GitHubRepo repoInfo = service.getRepoInfo("repo");31 MatcherAssert.assertThat(repoInfo.getName(), equalTo("spring-boot"));32 }33 @Test34 public void getGitHubRepos_fetchesGuideReposGitHub() {35 BDDMockito.given(ghClient.sendRequestForJson(ArgumentMatchers.anyString(), ArgumentMatchers.anyVararg())).willReturn(Fixtures.githubRepoListJson());36 GitHubRepo[] repos = service.findAllRepositories();37 MatcherAssert.assertThat(repos[0].getName(), equalTo("gs-rest-service"));38 }39 @Test40 public void shouldFindByPrefix() throws Exception {41 BDDMockito.given(ghClient.sendRequestForJson(ArgumentMatchers.anyString(), ArgumentMatchers.anyVararg())).willReturn(Fixtures.githubRepoListJson());42 List<GitHubRepo> matches = service.findRepositoriesByPrefix(REPO_PREFIX);43 MatcherAssert.assertThat(matches.size(), greaterThan(0));44 for (GitHubRepo match : matches) {45 MatcherAssert.assertThat(match.getName(), CoreMatchers.startsWith(REPO_PREFIX));46 }47 }48}...
Source:VarargsAndAnyObjectPicksUpExtraInvocationsTest.java
...19 // when20 table.newRow("qux", "foo", "bar", "baz");21 table.newRow("abc", "def");22 // then23 Mockito.verify(table, Mockito.times(2)).newRow(ArgumentMatchers.anyString(), ((String[]) (ArgumentMatchers.anyVararg())));24 }25 @Test26 public void shouldVerifyCorrectlyNumberOfInvocationsUsingAnyVarargAndEqualArgument() {27 // when28 table.newRow("x", "foo", "bar", "baz");29 table.newRow("x", "def");30 // then31 Mockito.verify(table, Mockito.times(2)).newRow(ArgumentMatchers.eq("x"), ((String[]) (ArgumentMatchers.anyVararg())));32 }33 @Test34 public void shouldVerifyCorrectlyNumberOfInvocationsWithVarargs() {35 // when36 table.newRow("qux", "foo", "bar", "baz");37 table.newRow("abc", "def");38 // then39 Mockito.verify(table).newRow(ArgumentMatchers.anyString(), ArgumentMatchers.eq("foo"), ArgumentMatchers.anyString(), ArgumentMatchers.anyString());40 Mockito.verify(table).newRow(ArgumentMatchers.anyString(), ArgumentMatchers.anyString());41 }42}...
Source:VarargsNotPlayingWithAnyObjectTest.java
...20 public void shouldMatchAnyVararg() {21 mock.run("a", "b");22 Mockito.verify(mock).run(ArgumentMatchers.anyString(), ArgumentMatchers.anyString());23 Mockito.verify(mock).run(((String) (ArgumentMatchers.anyObject())), ((String) (ArgumentMatchers.anyObject())));24 Mockito.verify(mock).run(((String[]) (ArgumentMatchers.anyVararg())));25 Mockito.verify(mock, Mockito.never()).run();26 Mockito.verify(mock, Mockito.never()).run(ArgumentMatchers.anyString(), ArgumentMatchers.eq("f"));27 }28 @Test29 public void shouldAllowUsingAnyObjectForVarArgs() {30 mock.run("a", "b");31 Mockito.verify(mock).run(((String[]) (ArgumentMatchers.anyObject())));32 }33 @Test34 public void shouldStubUsingAnyVarargs() {35 Mockito.when(mock.run(((String[]) (ArgumentMatchers.anyVararg())))).thenReturn("foo");36 Assert.assertEquals("foo", mock.run("a", "b"));37 }38}...
anyVararg
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyVararg;2import static org.mockito.ArgumentMatchers.anyInt;3import static org.mockito.ArgumentMatchers.anyString;4import static org.mockito.ArgumentMatchers.any;5import static org.mockito.ArgumentMatchers.anyList;6import static org.mockito.ArgumentMatchers.anyMap;7import static org.mockito.ArgumentMatchers.anySet;8import static org.mockito.ArgumentMatchers.anyCollection;9import static org.mockito.ArgumentMatchers.anyIterable;10import static org.mockito.ArgumentMatchers.anyCharSequence;11import static org.mockito.ArgumentMatchers.anyBoolean;12import static org.mockito.ArgumentMatchers.anyByte;13import static org.mockito.ArgumentMatchers.anyLong;14import static org.mockito.ArgumentMatchers.anyShort;15import static org.mockito.ArgumentMatchers.anyFloat;16import static org.mockito.ArgumentMatchers.anyDouble;17import static org.mockito.ArgumentMatchers.anyChar;18import static org.mockito.ArgumentMatchers.anyByte;19import static org.mockito.ArgumentMatchers.any;20import static org.mockito.ArgumentMatchers.anyVararg;21import static org.mockito.ArgumentM
anyVararg
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyVararg;2import static org.mockito.ArgumentMatchers.any;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import static org.mockito.Mockito.verify;6import java.util.List;7import org.junit.Test;8public class Test1 {9 public void test() {10 List mockedList = mock(List.class);11 when(mockedList.get(anyVararg())).thenReturn("Hello World");12 System.out.println(mockedList.get(1, 2, 3));13 verify(mockedList).get(1, 2, 3);14 }15}16Mockito: How to use anyInt() method of org.mockito.ArgumentMatchers class?17Mockito: How to use anyDouble() method of org.mockito.ArgumentMatchers class?18Mockito: How to use anyLong() method of org.mockito.ArgumentMatchers class?19Mockito: How to use anyFloat() method of org.mockito.ArgumentMatchers class?20Mockito: How to use anyString() method of org.mockito.ArgumentMatchers class?21Mockito: How to use anyObject() method of org.mockito.ArgumentMatchers class?22Mockito: How to use anyCollection() method of org.mockito.ArgumentMatchers class?23Mockito: How to use anyList() method of org.mockito.ArgumentMatchers class?24Mockito: How to use anySet() method of org.mockito.ArgumentMatchers class?25Mockito: How to use anyMap() method of org.mockito.ArgumentMatchers class?26Mockito: How to use anyVararg() method of org.mockito.ArgumentMatchers class?27Mockito: How to use anyBoolean() method of org.mockito.ArgumentMatchers class?28Mockito: How to use anyByte() method of org.mockito.ArgumentMatchers class?29Mockito: How to use anyChar() method of org.mockito.ArgumentMatchers class?30Mockito: How to use anyShort() method of org.mockito.ArgumentMatchers class?31Mockito: How to use any(Class) method of org.mockito.ArgumentMatchers class?32Mockito: How to use any(Class) method
anyVararg
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2public class AnyVararg {3 public static void main(String[] args) {4 ArgumentMatchers.anyVararg();5 }6}7Exception in thread "main" java.lang.NoSuchMethodError: org.mockito.ArgumentMatchers.anyVararg()V8 at AnyVararg.main(1.java:7)
anyVararg
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyVararg;2import java.util.List;3import java.util.Map;4import org.mockito.Mockito;5public class MockitoTest {6 public static void main(String[] args) {7 Map map = Mockito.mock(Map.class);8 Mockito.when(map.get(anyVararg())).thenReturn("any vararg");9 System.out.println(map.get(1, 2, 3));10 }11}
anyVararg
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import java.util.*;3import org.mockito.Mockito;4import static org.mockito.Mockito.*;5import static org.mockito.ArgumentMatchers.*;6public class anyVararg {7 public static void main(String[] args) {8 List<String> mockList = mock(List.class);9 when(mockList.addAll(anyVararg())).thenReturn(true);10 mockList.addAll(Arrays.asList("one", "two"));11 verify(mockList).addAll(Arrays.asList("one", "two"));12 }13}14Recommended Posts: Mockito any() Method in Java15Mockito anyInt() Method in Java16Mockito anyString() Method in Java17Mockito anyList() Method in Java18Mockito anyMap() Method in Java19Mockito anySet() Method in Java20Mockito anyCollection() Method in Java21Mockito anyBoolean() Method in Java22Mockito anyByte() Method in Java23Mockito anyChar() Method in Java24Mockito anyDouble() Method in Java25Mockito anyFloat() Method in Java26Mockito anyLong() Method in Java27Mockito anyShort() Method in Java28Mockito anyVararg() Method in Java29Mockito any() Method in Kotlin30Mockito anyInt() Method in Kotlin31Mockito anyString() Method in Kotlin32Mockito anyList() Method in Kotlin33Mockito anyMap() Method in Kotlin34Mockito anySet() Method in Kotlin35Mockito anyCollection() Method in Kotlin36Mockito anyBoolean() Method in Kotlin37Mockito anyByte() Method in Kotlin38Mockito anyChar() Method in Kotlin39Mockito anyDouble() Method in Kotlin40Mockito anyFloat() Method in Kotlin41Mockito anyLong() Method in Kotlin42Mockito anyShort() Method in Kotlin43Mockito anyVararg() Method in Kotlin44Mockito any() Method in Scala45Mockito anyInt() Method in Scala46Mockito anyString() Method in Scala47Mockito anyList() Method in Scala48Mockito anyMap() Method in Scala49Mockito anySet() Method in Scala50Mockito anyCollection() Method in Scala51Mockito anyBoolean() Method in Scala52Mockito anyByte() Method in Scala
anyVararg
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mock;3import org.mockito.Mockito;4import org.mockito.MockitoAnnotations;5import org.mockito.stubbing.Answer;6public class AnyVarargDemo {7 private Answer<Integer> answer;8 public static void main(String[] args) {9 MockitoAnnotations.initMocks(AnyVarargDemo.class);10 AnyVarargDemo demo = new AnyVarargDemo();11 demo.answer();12 }13 public void answer() {14 Mockito.when(answer.answer(ArgumentMatchers.anyVararg())).thenReturn(1);15 System.out.println("answer: " + answer.answer(1, 2, 3, 4));16 }17}18org.mockito.ArgumentMatchers.anyVararg() method19org.mockito.ArgumentMatchers.anyVararg() method signature20public static <T> T anyVararg()21import org.mockito.ArgumentMatchers;22import org.mockito.Mock;23import org.mockito.Mockito;24import org.mockito.MockitoAnnotations;25import org.mockito.stubbing.Answer;26public class AnyVarargDemo {27 private Answer<Integer> answer;28 public static void main(String[] args) {29 MockitoAnnotations.initMocks(AnyVarargDemo.class);30 AnyVarargDemo demo = new AnyVarargDemo();31 demo.answer();32 }33 public void answer() {34 Mockito.when(answer.answer(ArgumentMatchers.anyVararg())).thenReturn(1);35 System.out.println("answer: " + answer.answer(1, 2, 3, 4));36 }37}38org.mockito.ArgumentMatchers.any() method39org.mockito.ArgumentMatchers.any() method signature40public static <T> T any()41import org.mockito.ArgumentMatchers;42import org.mockito.Mock;43import org.mockito.Mockito;44import org.mockito.MockitoAnnotations;45import org.mockito.stubbing.Answer;
anyVararg
Using AI Code Generation
1public class ArgumentMatchers {2 private ArgumentMatchers() {3 }4 public static Object anyVararg() {5 return Matchers.anyVararg();6 }7}8public class ArgumentMatchers {9 private ArgumentMatchers() {10 }11 public static Object anyVararg() {12 return Matchers.anyVararg();13 }14}15public class ArgumentMatchers {16 private ArgumentMatchers() {17 }18 public static Object anyVararg() {19 return Matchers.anyVararg();20 }21}22public class ArgumentMatchers {23 private ArgumentMatchers() {24 }25 public static Object anyVararg() {26 return Matchers.anyVararg();27 }28}29public class ArgumentMatchers {30 private ArgumentMatchers() {31 }32 public static Object anyVararg() {33 return Matchers.anyVararg();34 }35}36public class ArgumentMatchers {37 private ArgumentMatchers() {38 }39 public static Object anyVararg() {40 return Matchers.anyVararg();41 }42}43public class ArgumentMatchers {44 private ArgumentMatchers() {45 }46 public static Object anyVararg() {47 return Matchers.anyVararg();48 }49}50public class ArgumentMatchers {51 private ArgumentMatchers() {52 }53 public static Object anyVararg() {54 return Matchers.anyVararg();55 }56}57public class ArgumentMatchers {58 private ArgumentMatchers() {59 }60 public static Object anyVararg() {61 return Matchers.anyVararg();62 }63}64public class ArgumentMatchers {65 private ArgumentMatchers() {
anyVararg
Using AI Code Generation
1import org.mockito.ArgumentMatchers.anyVararg;2public class Test {3 public static void main(String[] args) {4 mockObject.someMethod(anyVararg());5 }6}7import org.mockito.Matchers.anyVararg;8public class Test {9 public static void main(String[] args) {10 mockObject.someMethod(anyVararg());11 }12}13In the above code, we have used anyVararg() method of org.mockito.ArgumentMatchers class and org.mockito.Matchers class. The output of the above code is as follows:
anyVararg
Using AI Code Generation
1public class Test {2 public void test() {3 ArgumentMatchers.anyVararg();4 }5}6symbol: method anyVararg()7Hi, I have the same problem with the method anyVararg() of the class ArgumentMatchers. Is there any workaround for this?
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!!