Best Mockito code snippet using org.mockito.ArgumentMatchers.isNotNull
Source:DirectoryExceptionHandlerTest.java  
...76			ResponseEntity<Object> actual = handler.handleAccessDenied(exception);7778			//then79			Assertions.assertThat(actual)80					.isNotNull()81					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)82					.containsExactly(expected.getStatusCode(), expected.getBody());83		}8485		@Test86		void givenUncheckedIOExceptionAndMessageCodeNotTranslated_whenHandleException_thenReturnErrorWithMessageCode() {87			//given88			String messageCode = "io.accessdenied";89			ErrorInformation error = ErrorInformation.builder().message(messageCode).extraInformation(exceptionMessage).build();90			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);9192			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))93					.thenThrow(NoSuchMessageException.class);9495			//when96			ResponseEntity<Object> actual = handler.handleAccessDenied(exception);9798			//then99			Assertions.assertThat(actual)100					.isNotNull()101					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)102					.containsExactly(expected.getStatusCode(), expected.getBody());103		}104105		@Test106		void givenUncheckedIOExceptionWithCause_whenHandleException_thenReturnErrorWithExtraInformationCause() {107			//given108			ErrorInformation error = ErrorInformation.builder().message(translatedMessage).extraInformation(exceptionCauseMessage).build();109			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);110111			Mockito.when(exception.getCause()).thenReturn(Mockito.mock(IOException.class));112			Mockito.when(exception.getCause().getMessage()).thenReturn(exceptionCauseMessage);113			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))114					.thenReturn(translatedMessage);115116			//when117			ResponseEntity<Object> actual = handler.handleAccessDenied(exception);118119			//then120			Assertions.assertThat(actual)121					.isNotNull()122					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)123					.containsExactly(expected.getStatusCode(), expected.getBody());124		}125	}126127	@Nested128	class NoSuchFile {129130		@Mock131		private NoSuchFileException exception;132133		@BeforeEach134		void setUp() {135			Mockito.when(exception.getMessage()).thenReturn(exceptionMessage);136		}137138		@Test139		void givenUncheckedIOExceptionAndMessageCodeTranslated_whenHandleException_thenReturnErrorWithMessageTranslated() {140			//given141			ErrorInformation error = ErrorInformation.builder().message(translatedMessage).extraInformation(exceptionMessage).build();142			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))143					.thenReturn(translatedMessage);144			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);145146			//when147			ResponseEntity<Object> actual = handler.handleNoSuchFileException(exception);148149			//then150			Assertions.assertThat(actual)151					.isNotNull()152					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)153					.containsExactly(expected.getStatusCode(), expected.getBody());154		}155156		@Test157		void givenUncheckedIOExceptionAndMessageCodeNotTranslated_whenHandleException_thenReturnErrorWithMessageCode() {158			//given159			String messageCode = "io.nosuchfileexception";160			ErrorInformation error = ErrorInformation.builder().message(messageCode).extraInformation(exceptionMessage).build();161			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);162163			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))164					.thenThrow(NoSuchMessageException.class);165166			//when167			ResponseEntity<Object> actual = handler.handleNoSuchFileException(exception);168169			//then170			Assertions.assertThat(actual)171					.isNotNull()172					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)173					.containsExactly(expected.getStatusCode(), expected.getBody());174		}175176		@Test177		void givenUncheckedIOExceptionWithCause_whenHandleException_thenReturnErrorWithExtraInformationCause() {178			//given179			ErrorInformation error = ErrorInformation.builder().message(translatedMessage).extraInformation(exceptionCauseMessage).build();180			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);181182			Mockito.when(exception.getCause()).thenReturn(Mockito.mock(IOException.class));183			Mockito.when(exception.getCause().getMessage()).thenReturn(exceptionCauseMessage);184			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))185					.thenReturn(translatedMessage);186187			//when188			ResponseEntity<Object> actual = handler.handleNoSuchFileException(exception);189190			//then191			Assertions.assertThat(actual)192					.isNotNull()193					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)194					.containsExactly(expected.getStatusCode(), expected.getBody());195		}196	}197198	@Nested199	class InvalidPath {200201		@Mock202		private InvalidPathException exception;203204		@BeforeEach205		void setUp() {206			Mockito.when(exception.getMessage()).thenReturn(exceptionMessage);207		}208209		@Test210		void givenUncheckedIOExceptionAndMessageCodeTranslated_whenHandleException_thenReturnErrorWithMessageTranslated() {211			//given212			ErrorInformation error = ErrorInformation.builder().message(translatedMessage).extraInformation(exceptionMessage).build();213			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))214					.thenReturn(translatedMessage);215			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);216217			//when218			ResponseEntity<Object> actual = handler.handleInvalidPathException(exception);219220			//then221			Assertions.assertThat(actual)222					.isNotNull()223					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)224					.containsExactly(expected.getStatusCode(), expected.getBody());225		}226227		@Test228		void givenUncheckedIOExceptionAndMessageCodeNotTranslated_whenHandleException_thenReturnErrorWithMessageCode() {229			//given230			String messageCode = "io.invalidpathexception";231			ErrorInformation error = ErrorInformation.builder().message(messageCode).extraInformation(exceptionMessage).build();232			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);233234			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))235					.thenThrow(NoSuchMessageException.class);236237			//when238			ResponseEntity<Object> actual = handler.handleInvalidPathException(exception);239240			//then241			Assertions.assertThat(actual)242					.isNotNull()243					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)244					.containsExactly(expected.getStatusCode(), expected.getBody());245		}246247		@Test248		void givenUncheckedIOExceptionWithCause_whenHandleException_thenReturnErrorWithExtraInformationCause() {249			//given250			ErrorInformation error = ErrorInformation.builder().message(translatedMessage).extraInformation(exceptionCauseMessage).build();251			ResponseEntity<Object> expected = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);252253			Mockito.when(exception.getCause()).thenReturn(Mockito.mock(IOException.class));254			Mockito.when(exception.getCause().getMessage()).thenReturn(exceptionCauseMessage);255			Mockito.when(messageSource.getMessage(ArgumentMatchers.anyString(), ArgumentMatchers.any(Object[].class), ArgumentMatchers.any(Locale.class)))256					.thenReturn(translatedMessage);257258			//when259			ResponseEntity<Object> actual = handler.handleInvalidPathException(exception);260261			//then262			Assertions.assertThat(actual)263					.isNotNull()264					.extracting(ResponseEntity::getStatusCode, ResponseEntity::getBody)265					.containsExactly(expected.getStatusCode(), expected.getBody());266		}267	}268}
...Source:UserServiceTest.java  
...60		Mono<User> expect = Mono.just(mockData);61		when(repository.findOne(ArgumentMatchers.<Example<User>>any())).thenReturn(expect);62		Mono<User> test = service.findOneByUsername("username");63		64		assertThat(test).isNotNull().isEqualTo(expect);65		verify(repository, times(1)).findOne(ArgumentMatchers.<Example<User>>any());66		verifyNoMoreInteractions(repository);67	}68	69	@Test70	void test_findAll() {71		Flux<User> expect = Flux.just(mockData);72		when(repository.findAll(ArgumentMatchers.<Example<User>>any())).thenReturn(expect);73		Flux<User> test = service.findAll("false");74		75		assertThat(test).isNotNull().isEqualTo(expect);76		verify(repository, times(1)).findAll(ArgumentMatchers.<Example<User>>any());77		verifyNoMoreInteractions(repository);78	}79	80	@Test81	void test_add_withOut_createdAt() {82		Mono<User> expect = Mono.just(mockData);83		when(repository.insert(any(User.class))).thenReturn(expect);84		Mono<User> test = service.add(mockData);85		86		create(test)87			.expectNextMatches(response -> (response.getCreatedAt() != null) && (response.getUpdatedAt() != null))88			.expectComplete()89			.verify();90		91		assertThat(test).isNotNull().isEqualTo(expect);92		verify(repository, times(1)).insert(any(User.class));93	}94	95	@Test96	void test_add_with_createdAt() {97		mockData.setCreatedAt("createdAt");98		mockData.setUpdatedAt("updatedAt");99		Mono<User> expect = Mono.just(mockData);100		when(repository.insert(any(User.class))).thenReturn(expect);101		Mono<User> test = service.add(mockData);102		103		create(test)104			.expectNextMatches(response -> (response.getCreatedAt() != null) && (response.getUpdatedAt() != null))105			.expectComplete()106			.verify();107		108		assertThat(test).isNotNull().isEqualTo(expect);109		verify(repository, times(1)).insert(any(User.class));110	}111	112	@Test113	void test_deleteAll() {114		Flux<User> mockUser = Flux.just(mockData);115		Mono<Void> expect = Mono.empty();116		when(repository.deleteAll(ArgumentMatchers.<Publisher<User>>any())).thenReturn(expect);117		Mono<Void> test = service.deleteAll(mockUser);118		119		assertThat(test).isNotNull().isEqualTo(expect);120		verify(repository, times(1)).deleteAll(ArgumentMatchers.<Publisher<User>>any());121		verifyNoMoreInteractions(repository);122	}123	124	@Test125	void test_validate_true() {126		Mono<User> expect = Mono.just(mockData);127		when(repository.findOne(ArgumentMatchers.<Example<User>>any())).thenReturn(expect);128		Mono<User> test = service.validate(mockMap);129		130		create(test)131			.expectNextMatches(response -> response.getSystemMessage() == null)132			.expectComplete()133			.verify();134		135		assertThat(test).isNotNull().isEqualTo(expect);136		verify(repository, times(1)).findOne(ArgumentMatchers.<Example<User>>any());137		verifyNoMoreInteractions(repository);138	}139	140	@Test141	void test_validate_false() {142		mockMap.put("token", "token");143		Mono<User> test = service.validate(mockMap);144		145		create(test)146			.expectNextMatches(response -> equalsIgnoreCase(response.getSystemMessage(), "TOKEN_E001"))147			.expectComplete()148			.verify();149		150		assertThat(test).isNotNull();151		verify(repository, times(0)).findOne(ArgumentMatchers.<Example<User>>any());152		verifyNoMoreInteractions(repository);153	}154	155	@Test156	void test_activate_system_message_empty() {157		Mono<User> expect = Mono.just(mockData);158		when(repository.save(any(User.class))).thenReturn(expect);159		Mono<User> test = service.activate(mockData);160		161		create(test)162			.expectNextMatches(response -> equalsIgnoreCase(response.getIsActivated(), "true"))163			.expectComplete()164			.verify();165		166		assertThat(test).isNotNull().isEqualTo(expect);167		verify(repository, times(1)).save(any(User.class));168		verifyNoMoreInteractions(repository);169	}170	171	@Test172	void test_activate_system_message_not_empty() {173		mockData.setSystemMessage("message");174		Mono<User> test = service.activate(mockData);175		176		create(test)177			.expectNextMatches(response -> isBlank(response.getIsActivated()))178			.expectComplete()179			.verify();180		181		assertThat(test).isNotNull();182		verify(repository, times(0)).save(any(User.class));183		verifyNoMoreInteractions(repository);184	}185	186	@Test187	void test_reactivate() {188		Mono<User> expect = Mono.just(mockData);189		when(repository.findOne(ArgumentMatchers.<Example<User>>any())).thenReturn(expect);190		Mono<User> test = service.reactivate(mockMap);191		192		create(test)193			.expectNextMatches(response -> isNotBlank(response.getEmail()) && equalsIgnoreCase(response.getEmail(), getString(mockMap, "email")))194			.expectComplete()195			.verify();196		197		assertThat(test).isNotNull();198		verify(repository, times(1)).findOne(ArgumentMatchers.<Example<User>>any());199		verifyNoMoreInteractions(repository);200	}201	202}...Source:ProductControllerTest.java  
...63    @Test64    void returnProductPageWhenSuccessful() {65        Page<ShowProduct> showProductPage = controller.findAll(null).getBody();66        String expectedProductName = ProductFactory.createShowProduct().getName();67        assertThat(showProductPage).isNotNull();68        assertThat(showProductPage.getContent()).isNotNull().isNotEmpty().hasSize(1);69        assertThat(showProductPage.getContent().get(0).getName()).isEqualTo(expectedProductName);70    }71    @DisplayName("Return a product to show when a valid ID is given")72    @Test73    void returnShowProductWhenFindByIdIsSuccessful() {74        ShowProduct showProduct = controller.findById(null).getBody();75        String expectedName = ProductFactory.createShowProduct().getName();76        assertThat(showProduct).isNotNull();77        assertThat(showProduct.getName()).isEqualTo(expectedName);78    }79    @DisplayName("Return a page of products when search is successful")80    @Test81    void returnShowProductPageWhenSearchIsSuccessful() {82        String expectedName = ProductFactory.createShowProduct().getName();83        Page<ShowProduct> showProductPage = controller.findByNameContaining(null, null).getBody();84        assertThat(showProductPage).isNotNull().isNotEmpty().hasSize(1);85        assertThat(showProductPage.getContent().get(0).getName()).isEqualTo(expectedName);86    }87    @DisplayName("Return an empty page of products when search is unsuccessful")88    @Test89    void returnAnEmptyShowProductPageWhenSearchIsUnsuccessful() {90        PageImpl<Product> productPage = new PageImpl<>(Collections.emptyList());91        BDDMockito.when(service.findByNameContaining(ArgumentMatchers.any(), ArgumentMatchers.anyString())).thenReturn(productPage);92        Page<ShowProduct> showProductPage = new PageImpl<>(Collections.emptyList());93        BDDMockito.when(mapper.convertFromProductPageToShowProductPage(ArgumentMatchers.any())).thenReturn(showProductPage);94        Page<ShowProduct> finalShowProductPage = controller.findByNameContaining(null, null).getBody();95        assertThat(finalShowProductPage).isNotNull().isEmpty();96    }97    @DisplayName("Return nothing when product is saved successful")98    @Test99    void returnNothingWhenProductIsSaved() {100        assertThatCode(() -> this.controller.save(null)).doesNotThrowAnyException();101        ResponseEntity<Void> responseEntity = this.controller.save(null);102        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED);103    }104    @DisplayName("Return exception when product is not found")105    @Test106    void returnExceptionWhenIdIsNotFound() {107        BDDMockito.when(service.findById(ArgumentMatchers.anyLong())).thenThrow(new ModelNotFoundException("Product not found"));108        assertThatThrownBy(() -> controller.findById(1L)).isInstanceOf(ModelNotFoundException.class).hasMessage("Product not found");109    }...Source:PurchaseControllerTest.java  
...45	@DisplayName("findById return a purchase when successful")46	void findById_ReturnPurchase_WhenSuccessful() {47		Purchase expectedPurchase = PurchaseCreator.createValidPurchase();48		Purchase purchase = purchaseController.findById(1).getBody();49		Assertions.assertThat(purchase).isNotNull();50		Assertions.assertThat(purchase.getId()).isEqualTo(expectedPurchase.getId());51		Assertions.assertThat(purchase.getDescription()).isEqualTo(expectedPurchase.getDescription());52	}53	@Test54	@DisplayName("getPrice return a json with price when successful")55	void getPrice_ReturnPrice_WhenSuccessful() {56		String price = purchaseController.getPrice(1).getBody();57		Assertions.assertThat(price).isNotNull().isNotEmpty();58		Assertions.assertThat(price).isEqualTo("{\"price\":1.0}");59	}60	@Test61	@DisplayName("closeOrder return a json with change when successful")62	void closeOrder_ReturnChange_WhenSuccessful() {63		String change = purchaseController.closeOrder(1, 2.0).getBody();64		Assertions.assertThat(change).isNotNull().isNotEmpty();65		Assertions.assertThat(change).isEqualTo("{\"change\":1.0}");66	}67	@Test68	@DisplayName("calcPrice return a json with price when successful")69	void calcPrice_ReturnPrice_WhenSuccessful() {70		String price = purchaseController.calcPrice(List.of(ProductDTOCreator.createValidProductDTO())).getBody();71		Assertions.assertThat(price).isNotNull().isNotEmpty();72		Assertions.assertThat(price).isEqualTo("{\"price\":1.0}");73	}74	@Test75	@DisplayName("create return a http status CREATED when successful")76	void create_ReturnCreated_WhenSuccessful() {77		ResponseEntity<PurchaseDTO> request = purchaseController.create(PurchaseCreator.createPurchaseToBeSaved());78		String location = request.getHeaders().getLocation().getPath();79		Assertions.assertThat(request).isNotNull();80		Assertions.assertThat(request.getBody()).isNotNull();81		Assertions.assertThat(request.getBody().getId()).isNotNull();82		83		Assertions.assertThat(request.getBody().getDescription()).isEqualTo(PurchaseCreator.createPurchaseToBeSaved().getDescription());84		Assertions.assertThat(location).isEqualTo("/" + PurchaseCreator.createValidPurchase().getId());85		Assertions.assertThat(request.getStatusCode()).isEqualTo(HttpStatus.CREATED);86	}87	@Test88	@DisplayName("addProduct return a http status CREATED when successful")89	void addProduct_ReturnCreated_WhenSuccessful() {90		ResponseEntity<Void> request = purchaseController91				.addProduct(PurchaseProductDTOCreator.createValidPurchaseProductDTO());92		String location = request.getHeaders().getLocation().getPath();93		Assertions.assertThat(request).isNotNull();94		Assertions.assertThat(request.getBody()).isNull();95		Assertions.assertThat(location)96				.isEqualTo("/purchase/" + PurchaseProductCreator.createValidPurchaseProduct().getId());97		Assertions.assertThat(request.getStatusCode()).isEqualTo(HttpStatus.CREATED);98	}99	@Test100	@DisplayName("delProduct return a http status NO_CONTENT when successful")101	void delProduct_ReturnCreated_WhenSuccessful() {102		ResponseEntity<Void> request = purchaseController103				.delProduct(PurchaseProductDTOCreator.createValidPurchaseProductDTO());104		Assertions.assertThat(request).isNotNull();105		Assertions.assertThat(request.getBody()).isNull();106		Assertions.assertThat(request.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);107	}108}...Source:PurchaseServiceTest.java  
...51	@DisplayName("findById return a purchase when successful")52	void findById_ReturnPurchase_WhenSuccessful() {53		Purchase expectedPurchase = PurchaseCreator.createValidPurchase();54		Purchase purchase = purchaseService.findById(1);55		Assertions.assertThat(purchase).isNotNull();56		Assertions.assertThat(purchase.getId()).isEqualTo(expectedPurchase.getId());57		Assertions.assertThat(purchase.getDescription()).isEqualTo(expectedPurchase.getDescription());58	}59	@Test60	@DisplayName("calculateTotalPrice return price when successful")61	void calculateTotalPrice_ReturnPrice_WhenSuccessful() {62		Double price = purchaseService.calculateTotalPrice(1);63		Assertions.assertThat(price).isNotNull();64		Assertions.assertThat(price).isEqualTo(1.0);65	}66	@Test67	@DisplayName("closeOrder return change when successful")68	void closeOrder_ReturnChange_WhenSuccessful() {69		Double change = purchaseService.closeOrder(1, 2.0);70		Assertions.assertThat(change).isNotNull();71		Assertions.assertThat(change).isEqualTo(1.0);72	}73	@Test74	@DisplayName("calcPrice return a json with price when successful")75	void calcPrice_ReturnPrice_WhenSuccessful() {76		Double price = purchaseService.calcPrice(List.of(ProductDTOCreator.createValidProductDTO()));77		Assertions.assertThat(price).isNotNull();78		Assertions.assertThat(price).isEqualTo(1.0);79	}80	@Test81	@DisplayName("create return a Purchase when successful")82	void create_ReturnPurchase_WhenSuccessful() {83		Purchase purchaseToBeSaved = PurchaseCreator.createPurchaseToBeSaved();84		Purchase purchaseSaved = purchaseService.create(purchaseToBeSaved);85		Assertions.assertThat(purchaseSaved).isNotNull();86		Assertions.assertThat(purchaseSaved.getId()).isNotNull();87		Assertions.assertThat(purchaseSaved.getDescription()).isEqualTo(purchaseToBeSaved.getDescription());88	}89	@Test90	@DisplayName("addProduct return a PurchaseProduct when successful")91	void addProduct_ReturnPurchaseProduct_WhenSuccessful() {92		BDDMockito93			.when(purchaseProductRepositoryMock.findByProduct_IdAndPurchase_Id(ArgumentMatchers.anyInt(),94					ArgumentMatchers.anyInt()))95			.thenReturn(Optional.empty());96		PurchaseProduct purchaseProduct = purchaseService97				.addProduct(PurchaseProductDTOCreator.createValidPurchaseProductDTO());98		Assertions.assertThat(purchaseProduct).isNotNull();99		Assertions.assertThat(purchaseProduct.getProduct()).isNotNull();100		Assertions.assertThat(purchaseProduct.getQuantity())101				.isEqualTo(PurchaseProductCreator.createValidPurchaseProduct().getQuantity());102	}103	@Test104	@DisplayName("delProduct does not throw any exception when successful")105	void delProduct_DoesNotThrowAnyException_WhenSuccessful() {106		purchaseService.delProduct(PurchaseProductDTOCreator.createValidPurchaseProductDTO());107		Assertions108				.assertThatCode(109						() -> purchaseService.delProduct(PurchaseProductDTOCreator.createValidPurchaseProductDTO()))110				.doesNotThrowAnyException();111	}112}...Source:AnimeControllerTest.java  
...43    @Test44    void listWithPagigationtest() {45        String expectedName = AnimeCreator.createValidAnime().getName();46        Page<Anime> animePage = animeController.list(null).getBody();47        Assertions.assertThat(animePage).isNotNull();48        Assertions.assertThat(animePage.toList()).isNotEmpty().hasSize(1);49        Assertions.assertThat(animePage.toList().get(0).getName()).isEqualTo(expectedName);50    }51    @Test52    void listAlltest() {53        String expectedName = AnimeCreator.createValidAnime().getName();54        List<Anime> animes = animeController.listAll().getBody();55        Assertions.assertThat(animes).isNotNull().isNotEmpty().hasSize(1);56        Assertions.assertThat(animes.get(0).getName()).isEqualTo(expectedName);57    }58    @Test59    void findByIdTest() {60        Integer expectedId = AnimeCreator.createValidAnime().getId();61        Anime anime = animeController.findById(0).getBody();62        Assertions.assertThat(anime).isNotNull();63        Assertions.assertThat(anime.getId()).isNotNull().isEqualTo(expectedId);64    }65    @Test66    void findByNameTest() {67        String expectedName = AnimeCreator.createValidAnime().getName();68        List<Anime> animes = animeController.findByName("anime").getBody();69        Assertions.assertThat(animes).isNotNull().isNotEmpty().hasSize(1);70        Assertions.assertThat(animes.get(0).getName()).isEqualTo(expectedName);71    }72    @Test73    void findByNameExceptionTest() {74        BDDMockito.when(animeServiceMock.findByName(ArgumentMatchers.anyString())).thenReturn(Collections.emptyList());75        String expectedName = AnimeCreator.createValidAnime().getName();76        List<Anime> animes = animeController.findByName("anime").getBody();77        Assertions.assertThat(animes).isNotNull().isEmpty();78    }79    @Test80    void saveTest() {81        Anime anime = animeController.save(AnimePostDTOCreator.createAnimePostDTO()).getBody();82        Assertions.assertThat(anime).isNotNull().isEqualTo(AnimeCreator.createValidAnime());83    }84    @Test85    void updateTest() {86        Assertions.assertThatCode(() -> animeController.update(AnimePutDTOCreator.createAnimePutDTO())).doesNotThrowAnyException();87        ResponseEntity<Void> entity = animeController.update(AnimePutDTOCreator.createAnimePutDTO());88        Assertions.assertThat(entity).isNotNull();89        Assertions.assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);90    }91    @Test92    void deleteTest() {93        Assertions.assertThatCode(() -> animeController.delete(1)).doesNotThrowAnyException();94        ResponseEntity<Void> entity = animeController.delete(1);95        Assertions.assertThat(entity).isNotNull();96        Assertions.assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);97    }98}...Source:ProductsControllerTest.java  
...43    @DisplayName("listAll returns list of products when successful")44    void listAllProducts() {45        ProductsBean productsBean = ProductsBeanTest.productsBean();46        Products products = productsController.create(productsBean).getBody();47        Assertions.assertThat(products).isNotNull();48        List<Products> list = productsController.getAll().getBody();49        Assertions.assertThat(list).isNotNull().isNotEmpty();50    }51    @Test52    @DisplayName("get Product by id and return a product when successful")53    void getOne() {54        ResponseEntity<Products> one = productsController.getOne(10L);55        Assertions.assertThat(one.getStatusCode()).isEqualTo(HttpStatus.OK);56        Assertions.assertThat(one).isNotNull();57        Assertions.assertThat(one.getBody()).isEqualTo(ProductsBeanTest.toEntity().get(0));58    }59    @Test60    @DisplayName("create a product and return a product when successful")61    void createProduct() {62        ProductsBean productsBean = ProductsBeanTest.productsBean();63        ResponseEntity<Products> responseEntity = productsController.create(productsBean);64        Assertions.assertThat(responseEntity).isNotNull();65        Assertions.assertThat(responseEntity.getBody()).isNotNull();66        Assertions.assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED);67        Assertions.assertThat(responseEntity.getBody().getId()).isEqualTo(1L);68    }69    @Test70    @DisplayName("update a product and return a update product when successful")71    void updateProduct() {72        ProductsBean bean = ProductsBeanTest.productsBean();73        Assertions.assertThatCode(() -> productsController.update(1L, bean)).doesNotThrowAnyException();74        bean.setDescription("produtos");75        ResponseEntity<Products> update = productsController.update(2L, bean);76        Assertions.assertThat(update).isNotNull();77        Assertions.assertThat(update.getBody()).isNotNull();78        Assertions.assertThat(update.getStatusCode()).isEqualTo(HttpStatus.OK);79        Assertions.assertThat(update.getBody().getName()).isEqualTo("produtos");80    }81    @Test82    @DisplayName("search with Params [q, min_price, max_price] then returns a List of Products")83    void searchProduct(){84        ResponseEntity<List<Products>> teste = productsController.search("TESTE", 10.0, 15.00);85        Assertions.assertThat(teste).isNotNull();86        Assertions.assertThat(teste.getBody()).isNotNull();87        Assertions.assertThat(teste.getStatusCode()).isEqualTo(HttpStatus.OK);88        Assertions.assertThat(teste.getBody()).isEqualTo(ProductsBeanTest.toEntity());89        Assertions.assertThat(teste.getBody()).hasSize(1);90    }91    @Test92    @DisplayName("delete a Product")93    void deleteProduct(){94        ResponseEntity<Void> teste = productsController.delete(10L);95        Assertions.assertThat(teste).isNotNull();96        Assertions.assertThat(teste.getStatusCode()).isEqualTo(HttpStatus.OK);97    }98}...Source:AnimeServiceTest.java  
...41    @Test42    void listAllWithPaginationtest() {43        String expectedName = AnimeCreator.createValidAnime().getName();44        Page<Anime> animePage = animeService.listAll(PageRequest.of(1,1));45        Assertions.assertThat(animePage).isNotNull();46        Assertions.assertThat(animePage.toList()).isNotEmpty().hasSize(1);47        Assertions.assertThat(animePage.toList().get(0).getName()).isEqualTo(expectedName);48    }49    @Test50    void listAlltest() {51        String expectedName = AnimeCreator.createValidAnime().getName();52        List<Anime> animes = animeService.listAllNonPageable();53        Assertions.assertThat(animes).isNotNull().isNotEmpty().hasSize(1);54        Assertions.assertThat(animes.get(0).getName()).isEqualTo(expectedName);55    }56    @Test57    void findByIdTest() {58        Integer expectedId = AnimeCreator.createValidAnime().getId();59        Anime anime = animeService.findById(0);60        Assertions.assertThat(anime).isNotNull();61        Assertions.assertThat(anime.getId()).isNotNull().isEqualTo(expectedId);62    }63    @Test64    void findByIdExceptionTest() {65        BDDMockito.when(animeRepositoryMock.findById(ArgumentMatchers.anyInt())).thenReturn(Optional.empty());66        Assertions.assertThatExceptionOfType(BadRequestException.class).isThrownBy(() -> animeService.findById(1));67    }68    @Test69    void findByNameTest() {70        String expectedName = AnimeCreator.createValidAnime().getName();71        List<Anime> animes = animeService.findByName("anime");72        Assertions.assertThat(animes).isNotNull().isNotEmpty().hasSize(1);73        Assertions.assertThat(animes.get(0).getName()).isEqualTo(expectedName);74    }75    @Test76    void findByNameExceptionTest() {77        BDDMockito.when(animeRepositoryMock.findByName(ArgumentMatchers.anyString())).thenReturn(Collections.emptyList());78        String expectedName = AnimeCreator.createValidAnime().getName();79        List<Anime> animes = animeService.findByName("anime");80        Assertions.assertThat(animes).isNotNull().isEmpty();81    }82    @Test83    void saveTest() {84        Anime anime = animeService.save(AnimePostDTOCreator.createAnimePostDTO());85        Assertions.assertThat(anime).isNotNull().isEqualTo(AnimeCreator.createValidAnime());86    }87    @Test88    void updateTest() {89        Assertions.assertThatCode(() -> animeService.update(AnimePutDTOCreator.createAnimePutDTO())).doesNotThrowAnyException();90    }91    @Test92    void deleteTest() {93        Assertions.assertThatCode(() -> animeService.delete(1)).doesNotThrowAnyException();94    }95}...isNotNull
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.Mock;4import org.mockito.junit.MockitoJUnitRunner;5import java.util.List;6import static org.mockito.Mockito.verify;7@RunWith(MockitoJUnitRunner.class)8public class IsNotNullTest {9    private List<String> list;10    public void testIsNotNull() {11        list.add("one");12        verify(list).add(org.mockito.ArgumentMatchers.isNotNull());13    }14}15-> at IsNotNullTest.testIsNotNull(IsNotNullTest.java:22)16import org.junit.Test;17import org.junit.runner.RunWith;18import org.mockito.Mock;19import org.mockito.junit.MockitoJUnitRunner;20import java.util.List;21import static org.mockito.Mockito.verify;22@RunWith(MockitoJUnitRunner.class)23public class IsNotNullTest {24    private List<String> list;25    public void testIsNotNull() {26        list.add("one");27        verify(list).add(org.mockito.ArgumentMatchers.isNotNull());28    }29}isNotNull
Using AI Code Generation
1public class 1 {2    public static void main(String[] args) {3        List<String> mockedList = mock(List.class);4        when(mockedList.get(anyInt())).thenReturn("element");5        System.out.println(mockedList.get(999));6        verify(mockedList).get(isNotNull());7    }8}9Argument(s) are different! Wanted:10mockedList.get(11);12-> at 1.main(1.java:11)13mockedList.get(14);15-> at 1.main(1.java:8)16public class 2 {17    public static void main(String[] args) {18        List<String> mockedList = mock(List.class);19        when(mockedList.get(anyInt())).thenReturn("element");20        System.out.println(mockedList.get(999));21        verify(mockedList).get(isNull());22    }23}24-> at 2.main(2.java:11)25mockedList.get(26);27-> at 2.main(2.java:8)28public class 3 {29    public static void main(String[] args) {30        List<String> mockedList = mock(List.class);31        when(mockedList.get(anyInt())).thenReturn("element");32        System.out.println(mockedList.get(999));33        verify(mockedList).get(not(eq(999)));34    }35}36Argument(s) are different! Wanted:37mockedList.get(38    not(999)39);40-> at 3.main(3.java:11)41mockedList.get(42);43-> at 3.main(3.java:8)isNotNull
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mock;3import org.mockito.Mockito;4import org.mockito.MockitoAnnotations;5import org.mockito.Spy;6import org.testng.annotations.BeforeMethod;7import org.testng.annotations.Test;8public class MockitoNotNullTest {9    private String str;10    private String spyStr;11    public void init() {12        MockitoAnnotations.initMocks(this);13    }14    public void testNotNull() {15        Mockito.when(str.equals(ArgumentMatchers.isNotNull())).thenReturn(true);16        Mockito.when(spyStr.equals(ArgumentMatchers.isNotNull())).thenReturn(true);17        System.out.println(str.equals("Hello"));18        System.out.println(spyStr.equals("Hello"));19    }20}isNotNull
Using AI Code Generation
1public class 1 {2    public void test1() {3        List<String> mockedList = mock(List.class);4        mockedList.add("one");5        verify(mockedList).add(isNotNull());6    }7}8org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:9mockedList.add(10    isNotNull()11);12-> at 1.test1(1.java:15)13mockedList.add(14);15-> at 1.test1(1.java:12)16public class 2 {17    public void test1() {18        List<String> mockedList = mock(List.class);19        mockedList.add("one");20        verify(mockedList).add(isNotNull(String.class));21    }22}23org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:24mockedList.add(25    isNotNull(java.lang.String.class)26);27-> at 2.test1(2.java:15)28mockedList.add(29);30-> at 2.test1(2.java:12)31public class 3 {32    public void test1() {33        List<String> mockedList = mock(List.class);34        mockedList.add("one");isNotNull
Using AI Code Generation
1public class MockitoNotNullTest {2    public void testMockitoNotNull() {3        List<String> mockedList = mock(List.class);4        when(mockedList.get(isNotNull())).thenReturn("Hello");5        assertEquals("Hello", mockedList.get(0));6        assertEquals("Hello", mockedList.get(1));7        assertEquals("Hello", mockedList.get(2));8    }9}isNotNull
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import static org.junit.Assert.*;3import org.junit.Test;4import static org.mockito.Mockito.*;5public class MockitoExample {6   public void test() {7      List mockedList = mock(List.class);8      when(mockedList.get(0)).thenReturn("first");9      mockedList.get(0);10      verify(mockedList).get(ArgumentMatchers.isNotNull());11   }12}13mockedList.get(14);15-> at MockitoExample.test(MockitoExample.java:17)isNotNull
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import static org.mockito.ArgumentMatchers.isNotNull;3public class MockitoIsNotNull {4    public static void main(String[] args) {5    }6}7import org.mockito.ArgumentMatchers;8import static org.mockito.ArgumentMatchers.isNull;9public class MockitoIsNull {10    public static void main(String[] args) {11    }12}13import org.mockito.ArgumentMatchers;14import static org.mockito.ArgumentMatchers.isA;15public class MockitoIsA {16    public static void main(String[] args) {17    }18}19import org.mockito.ArgumentMatchers;20import static org.mockito.ArgumentMatchers.isInstanceOf;21public class MockitoIsInstanceOf {22    public static void main(String[] args) {23    }24}25import org.mockito.ArgumentMatchers;26import static org.mockito.ArgumentMatchers.isNull;27public class MockitoIsNull {28    public static void main(String[] args) {29    }30}31import org.mockito.ArgumentMatchers;32import static org.mockito.ArgumentMatchers.isNotNull;33public class MockitoIsNotNull {34    public static void main(String[] args) {35    }36}37import org.mockito.ArgumentMatchers;38import static org.mockito.ArgumentMatchers.isNotNull;39public class MockitoIsNotNull {40    public static void main(String[] args) {41    }42}43import org.mockito.ArgumentMatchers;44import static org.mockito.ArgumentMatchers.isNotNull;45public class MockitoIsNotNull {46    public static void main(String[] args) {47    }48}49import org.mockito.ArgumentMatchers;50import static org.mockito.ArgumentMatchers.isNotNull;51public class MockitoIsNotNull {isNotNull
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import org.mockito.stubbing.Answer;4import org.mockito.stubbing.OngoingStubbing;5import java.util.List;6import java.util.Map;7import java.util.Set;8public class Test {9    public static void main(String[] args) {10        List<String> list = Mockito.mock(List.class);11        OngoingStubbing<String> stub = Mockito.when(list.get(ArgumentMatchers.isNotNull()));12        stub.thenAnswer((Answer<String>) invocation -> {13            Object[] args1 = invocation.getArguments();14            return "called with arguments: " + args1;15        });16        System.out.println(list.get(1));17        System.out.println(list.get(2));18        System.out.println(list.get(3));19    }20}21import org.mockito.ArgumentMatchers;22import org.mockito.Mockito;23import org.mockito.stubbing.Answer;24import org.mockito.stubbing.OngoingStubbing;25import java.util.List;26import java.util.Map;27import java.util.Set;28public class Test {29    public static void main(String[] args) {30        List<String> list = Mockito.mock(List.class);31        OngoingStubbing<String> stub = Mockito.when(list.get(ArgumentMatchers.isNotNull()));32        stub.thenAnswer((Answer<String>) invocation -> {33            Object[] args1 = invocation.getArguments();34            return "called with arguments: " + args1[0];35        });36        System.out.println(list.get(1));37        System.out.println(list.get(2));38        System.out.println(list.get(3));39    }40}41import org.mockito.ArgumentMatchers;42import org.mockito.Mockito;43import org.mockito.stubbing.Answer;44import org.mockito.stubbing.OngoingStubbing;45import java.util.List;46import java.util.Map;47import java.util.Set;48public class Test {49    public static void main(String[] args) {50        List<String> list = Mockito.mock(List.class);51        OngoingStubbing<String> stub = Mockito.when(list.get(ArgumentMatchers.isNotNull()));52        stub.thenAnswer((Answer<String>) invocation -> {isNotNull
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.ArgumentMatchers;4import org.mockito.InjectMocks;5import org.mockito.Mock;6import org.mockito.junit.MockitoJUnitRunner;7import static org.mockito.Mockito.verify;8@RunWith(MockitoJUnitRunner.class)9public class MockitoTest {10    private MyInterface myInterface;11    private MyService myService;12    public void test() {13        myService.doSomething("Hello");14        verify(myInterface).doSomething(ArgumentMatchers.isNotNull());15    }16}17import org.junit.Test;18import org.junit.runner.RunWith;19import org.mockito.ArgumentMatchers;20import org.mockito.InjectMocks;21import org.mockito.Mock;22import org.mockito.junit.MockitoJUnitRunner;23import static org.mockito.Mockito.verify;24@RunWith(MockitoJUnitRunner.class)25public class MockitoTest {26    private MyInterface myInterface;27    private MyService myService;28    public void test() {29        myService.doSomething("Hello");30        verify(myInterface).doSomething(ArgumentMatchers.notNull());31    }32}33import org.junit.Test;34import org.junit.runner.RunWith;35import org.mockito.ArgumentMatchers;36import org.mockito.InjectMocks;37import org.mockito.Mock;38import org.mockito.junit.MockitoJUnitRunner;39import static org.mockito.Mockito.verify;40@RunWith(MockitoJUnitRunner.class)41public class MockitoTest {42    private MyInterface myInterface;43    private MyService myService;44    public void test() {45        myService.doSomething("Hello");46        verify(myInterface).doSomething(ArgumentMatchers.notNull());47    }48}49importLearn 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!!
