Best Mockito code snippet using org.mockito.ArgumentMatchers.refEq
Source:MatchersMixin.java
...308 default <T> T nullable(Class<T> clazz) {309 return ArgumentMatchers.nullable(clazz);310 }311 /**312 * Delegate call to public static <T> T org.mockito.ArgumentMatchers.refEq(T,java.lang.String...)313 * {@link org.mockito.ArgumentMatchers#refEq(java.lang.Object,java.lang.String[])}314 */315 default <T> T refEq(T value, String... excludeFields) {316 return ArgumentMatchers.refEq(value, excludeFields);317 }318 /**319 * Delegate call to public static <T> T org.mockito.ArgumentMatchers.same(T)320 * {@link org.mockito.ArgumentMatchers#same(java.lang.Object)}321 */322 default <T> T same(T value) {323 return ArgumentMatchers.same(value);324 }325 /**326 * Delegate call to public static short org.mockito.ArgumentMatchers.shortThat(org.mockito.ArgumentMatcher<java.lang.Short>)327 * {@link org.mockito.ArgumentMatchers#shortThat(org.mockito.ArgumentMatcher)}328 */329 default short shortThat(ArgumentMatcher<Short> matcher) {330 return ArgumentMatchers.shortThat(matcher);...
Source:DepositsFetcherTest.java
...14import static java.util.Collections.emptyList;15import static org.assertj.core.api.Assertions.assertThat;16import static org.mockito.ArgumentMatchers.any;17import static org.mockito.ArgumentMatchers.argThat;18import static org.mockito.ArgumentMatchers.refEq;19import static org.mockito.Mockito.doReturn;20import static org.mockito.Mockito.inOrder;21import static org.mockito.Mockito.mock;22import static org.mockito.Mockito.verify;23import static org.mockito.Mockito.verifyNoMoreInteractions;24import static org.mockito.Mockito.when;25import com.google.common.primitives.Longs;26import java.math.BigInteger;27import java.util.List;28import org.apache.tuweni.bytes.Bytes;29import org.junit.jupiter.api.Test;30import org.mockito.ArgumentMatcher;31import org.mockito.InOrder;32import org.web3j.protocol.core.DefaultBlockParameter;33import org.web3j.protocol.core.methods.response.EthBlock;34import org.web3j.protocol.core.methods.response.Log;35import org.web3j.utils.Numeric;36import tech.pegasys.teku.infrastructure.async.SafeFuture;37import tech.pegasys.teku.infrastructure.async.StubAsyncRunner;38import tech.pegasys.teku.pow.api.Eth1EventsChannel;39import tech.pegasys.teku.pow.contract.DepositContract;40import tech.pegasys.teku.pow.contract.RejectedRequestException;41import tech.pegasys.teku.pow.event.DepositsFromBlockEvent;42public class DepositsFetcherTest {43 private static final int MAX_BLOCK_RANGE = 10_000;44 private final Eth1Provider eth1Provider = mock(Eth1Provider.class);45 private final Eth1EventsChannel eth1EventsChannel = mock(Eth1EventsChannel.class);46 private final DepositContract depositContract = mock(DepositContract.class);47 private final Eth1BlockFetcher eth1BlockFetcher = mock(Eth1BlockFetcher.class);48 private final StubAsyncRunner asyncRunner = new StubAsyncRunner();49 private final DepositFetcher depositFetcher =50 new DepositFetcher(51 eth1Provider,52 eth1EventsChannel,53 depositContract,54 eth1BlockFetcher,55 asyncRunner,56 MAX_BLOCK_RANGE);57 @Test58 void depositsInConsecutiveBlocks() {59 SafeFuture<List<DepositContract.DepositEventEventResponse>> depositEventsFuture =60 mockContractEventsInRange(0, 10);61 mockBlockForEth1Provider("0x1234", 1, 1000);62 mockBlockForEth1Provider("0x2345", 2, 1014);63 mockBlockForEth1Provider("0x5678", 5, 1014);64 depositEventsFuture.complete(65 List.of(66 mockDepositEventEventResponse(1, "0x1234", 1),67 mockDepositEventEventResponse(2, "0x1234", 1),68 mockDepositEventEventResponse(3, "0x2345", 2),69 mockDepositEventEventResponse(4, "0x5678", 5)));70 depositFetcher.fetchDepositsInRange(BigInteger.ZERO, BigInteger.valueOf(10)).join();71 final InOrder inOrder = inOrder(eth1EventsChannel, eth1BlockFetcher);72 inOrder.verify(eth1BlockFetcher).fetch(BigInteger.ZERO, BigInteger.ZERO);73 inOrder.verify(eth1EventsChannel).onDepositsFromBlock(argThat(isEvent(1, 2)));74 inOrder.verify(eth1EventsChannel).onDepositsFromBlock(argThat(isEvent(2, 1)));75 inOrder.verify(eth1BlockFetcher).fetch(BigInteger.valueOf(3), BigInteger.valueOf(4));76 inOrder.verify(eth1EventsChannel).onDepositsFromBlock(argThat(isEvent(5, 1)));77 inOrder.verify(eth1BlockFetcher).fetch(BigInteger.valueOf(6), BigInteger.valueOf(10));78 }79 @Test80 void shouldUseMultipleBatchesWhenRangeIsLarge() {81 final BigInteger fromBlockNumber = BigInteger.ZERO;82 final BigInteger toBlockNumber = BigInteger.valueOf(3 * MAX_BLOCK_RANGE - 10);83 final BigInteger batch1End = fromBlockNumber.add(BigInteger.valueOf(MAX_BLOCK_RANGE));84 final BigInteger batch2Start = batch1End.add(BigInteger.ONE);85 final BigInteger batch2End = batch2Start.add(BigInteger.valueOf(MAX_BLOCK_RANGE));86 final BigInteger batch3Start = batch2End.add(BigInteger.ONE);87 final SafeFuture<List<DepositContract.DepositEventEventResponse>> batch1Response =88 new SafeFuture<>();89 final SafeFuture<List<DepositContract.DepositEventEventResponse>> batch2Response =90 new SafeFuture<>();91 final SafeFuture<List<DepositContract.DepositEventEventResponse>> batch3Response =92 new SafeFuture<>();93 when(depositContract.depositEventInRange(any(), any()))94 .thenReturn(batch1Response)95 .thenReturn(batch2Response)96 .thenReturn(batch3Response);97 final SafeFuture<Void> result =98 depositFetcher.fetchDepositsInRange(fromBlockNumber, toBlockNumber);99 assertThat(result).isNotDone();100 verify(depositContract)101 .depositEventInRange(102 refEq(DefaultBlockParameter.valueOf(fromBlockNumber)),103 refEq(DefaultBlockParameter.valueOf(batch1End)));104 verifyNoMoreInteractions(depositContract);105 batch1Response.complete(emptyList());106 verify(depositContract)107 .depositEventInRange(108 refEq(DefaultBlockParameter.valueOf(batch2Start)),109 refEq(DefaultBlockParameter.valueOf(batch2End)));110 verifyNoMoreInteractions(depositContract);111 batch2Response.complete(emptyList());112 verify(depositContract)113 .depositEventInRange(114 refEq(DefaultBlockParameter.valueOf(batch3Start)),115 refEq(DefaultBlockParameter.valueOf(toBlockNumber)));116 verifyNoMoreInteractions(depositContract);117 batch3Response.complete(emptyList());118 verifyNoMoreInteractions(depositContract);119 }120 @Test121 void shouldReduceBatchSizeWhenRequestIsRejected() {122 final BigInteger fromBlockNumber = BigInteger.ZERO;123 final BigInteger toBlockNumber = BigInteger.valueOf(MAX_BLOCK_RANGE + 100);124 final SafeFuture<List<DepositContract.DepositEventEventResponse>> request1Response =125 new SafeFuture<>();126 final SafeFuture<List<DepositContract.DepositEventEventResponse>> request2Response =127 new SafeFuture<>();128 final SafeFuture<List<DepositContract.DepositEventEventResponse>> request3Response =129 new SafeFuture<>();130 when(depositContract.depositEventInRange(any(), any()))131 .thenReturn(request1Response)132 .thenReturn(request2Response)133 .thenReturn(request3Response);134 final SafeFuture<Void> result =135 depositFetcher.fetchDepositsInRange(fromBlockNumber, toBlockNumber);136 assertThat(result).isNotDone();137 // First tries to request a full size batch138 verify(depositContract)139 .depositEventInRange(140 refEq(DefaultBlockParameter.valueOf(fromBlockNumber)),141 refEq(DefaultBlockParameter.valueOf(BigInteger.valueOf(MAX_BLOCK_RANGE))));142 verifyNoMoreInteractions(depositContract);143 // But there are too many results144 request1Response.completeExceptionally(new RejectedRequestException("Nah mate"));145 // So it halves the batch size and retries146 asyncRunner.executeQueuedActions();147 final BigInteger endSuccessfulRange =148 fromBlockNumber.add(BigInteger.valueOf(MAX_BLOCK_RANGE / 2));149 verify(depositContract)150 .depositEventInRange(151 refEq(DefaultBlockParameter.valueOf(fromBlockNumber)),152 refEq(DefaultBlockParameter.valueOf(endSuccessfulRange)));153 verifyNoMoreInteractions(depositContract);154 // And that works155 request2Response.complete(emptyList());156 // So it increases the batch size by 10% to avoid getting stuck with a very small batch size157 asyncRunner.executeQueuedActions();158 verify(depositContract)159 .depositEventInRange(160 refEq(DefaultBlockParameter.valueOf(endSuccessfulRange.add(BigInteger.ONE))),161 refEq(DefaultBlockParameter.valueOf(toBlockNumber)));162 verifyNoMoreInteractions(depositContract);163 }164 private void mockBlockForEth1Provider(String blockHash, long blockNumber, long timestamp) {165 EthBlock.Block block = mock(EthBlock.Block.class);166 when(block.getTimestamp()).thenReturn(BigInteger.valueOf(timestamp));167 when(block.getNumber()).thenReturn(BigInteger.valueOf(blockNumber));168 when(block.getHash()).thenReturn(blockHash);169 when(eth1Provider.getGuaranteedEth1Block(blockHash))170 .thenReturn(SafeFuture.completedFuture(block));171 }172 private SafeFuture<List<DepositContract.DepositEventEventResponse>> mockContractEventsInRange(173 long fromBlockNumber, long toBlockNumber) {174 SafeFuture<List<DepositContract.DepositEventEventResponse>> safeFuture = new SafeFuture<>();175 doReturn(safeFuture)...
Source:MonitoredDecisionModelTest.java
...30import static org.junit.jupiter.api.Assertions.assertSame;31import static org.kie.kogito.monitoring.core.common.Constants.SKIP_MONITORING;32import static org.mockito.ArgumentMatchers.any;33import static org.mockito.ArgumentMatchers.eq;34import static org.mockito.ArgumentMatchers.refEq;35import static org.mockito.Mockito.mock;36import static org.mockito.Mockito.reset;37import static org.mockito.Mockito.times;38import static org.mockito.Mockito.verify;39import static org.mockito.Mockito.when;40class MonitoredDecisionModelTest {41 private static final String TEST_MODEL_NAME = "TestModel";42 private static final String TEST_SERVICE_NAME = "TestService";43 private DMNModel mockedDMNModel;44 private DMNResult mockedEvaluateAllResult;45 private DMNResult mockedEvaluateDecisionServiceResult;46 private DecisionModel mockedDecisionModel;47 private MonitoredDecisionModel testObject;48 private MeterRegistry meterRegistry;49 private DMNResultMetricsBuilder dmnResultMetricsBuilder;50 @BeforeEach51 void setup() {52 mockedDMNModel = mock(DMNModel.class);53 when(mockedDMNModel.getName()).thenReturn(TEST_MODEL_NAME);54 mockedEvaluateAllResult = mock(DMNResult.class);55 mockedEvaluateDecisionServiceResult = mock(DMNResult.class);56 mockedDecisionModel = mock(DecisionModel.class);57 mockDecisionModel(mockedDecisionModel, mockedDMNModel, mockedEvaluateAllResult, mockedEvaluateDecisionServiceResult);58 meterRegistry = mock(SimpleMeterRegistry.class);59 dmnResultMetricsBuilder = mock(DMNResultMetricsBuilder.class);60 testObject = new MonitoredDecisionModel(mockedDecisionModel, dmnResultMetricsBuilder);61 }62 @Test63 void testMonitoredDecisionModelNewContext() {64 Map<String, Object> inputSet1 = new HashMap<>();65 testObject.newContext(inputSet1);66 verify(mockedDecisionModel).newContext(refEq(inputSet1));67 }68 @Test69 void testMonitoredDecisionModelNewContextWithFEELPropertyAccessibleInput() {70 FEELPropertyAccessible inputSet2 = mock(FEELPropertyAccessible.class);71 testObject.newContext(inputSet2);72 verify(mockedDecisionModel).newContext(refEq(inputSet2));73 }74 @Test75 void testMonitoredDecisionModelGetDMNModel() {76 DMNModel outputModel = testObject.getDMNModel();77 verify(mockedDecisionModel).getDMNModel();78 assertSame(mockedDMNModel, outputModel);79 }80 @Test81 void testMonitoredDecisionModelEvaluateAll() {82 DMNContext ctx = mock(DMNContext.class);83 DMNResult res = testObject.evaluateAll(ctx);84 verify(mockedDecisionModel).evaluateAll(refEq(ctx));85 assertSame(mockedEvaluateAllResult, res);86 verify(dmnResultMetricsBuilder, times(1)).generateMetrics(refEq(mockedEvaluateAllResult), eq(TEST_MODEL_NAME));87 }88 @Test89 void testMonitoredDecisionModelEvaluateDecisionService() {90 DMNContext ctx = mock(DMNContext.class);91 DMNResult res = testObject.evaluateDecisionService(ctx, TEST_SERVICE_NAME);92 verify(mockedDecisionModel).evaluateDecisionService(refEq(ctx), eq(TEST_SERVICE_NAME));93 assertSame(mockedEvaluateDecisionServiceResult, res);94 verify(dmnResultMetricsBuilder, times(1)).generateMetrics(refEq(mockedEvaluateDecisionServiceResult), eq(TEST_MODEL_NAME));95 }96 @Test97 void testMonitoredDecisionModelWithSkipMonitoringMetadata() {98 DMNContext ctx = mock(DMNContext.class);99 when(ctx.getMetadata()).thenReturn(new DMNMetadata() {100 @Override101 public Object set(String s, Object o) {102 return null;103 }104 @Override105 public Object get(String s) {106 return null;107 }108 @Override109 public Map<String, Object> asMap() {110 Map<String, Object> map = new HashMap();111 map.put(SKIP_MONITORING, true);112 return map;113 }114 });115 DMNResult res = testObject.evaluateDecisionService(ctx, TEST_SERVICE_NAME);116 verify(mockedDecisionModel).evaluateDecisionService(refEq(ctx), eq(TEST_SERVICE_NAME));117 assertSame(mockedEvaluateDecisionServiceResult, res);118 verify(dmnResultMetricsBuilder, times(0)).generateMetrics(refEq(mockedEvaluateDecisionServiceResult), eq(TEST_MODEL_NAME));119 res = testObject.evaluateAll(ctx);120 verify(mockedDecisionModel).evaluateAll(refEq(ctx));121 assertSame(mockedEvaluateAllResult, res);122 verify(dmnResultMetricsBuilder, times(0)).generateMetrics(refEq(mockedEvaluateDecisionServiceResult), eq(TEST_MODEL_NAME));123 }124 private static void mockDecisionModel(DecisionModel mockedDecisionModel, DMNModel mockedDMNModel, DMNResult mockedEvaluateAllResult, DMNResult mockedEvaluateDecisionServiceResult) {125 reset(mockedDecisionModel);126 when(mockedDecisionModel.getDMNModel()).thenReturn(mockedDMNModel);127 when(mockedDecisionModel.evaluateAll(any())).thenReturn(mockedEvaluateAllResult);128 when(mockedDecisionModel.evaluateDecisionService(any(), eq(TEST_SERVICE_NAME))).thenReturn(mockedEvaluateDecisionServiceResult);129 }130}...
Source:SatRecruitmentControllerTest.java
...38 var result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/create-user")39 .contentType("application/json;charset=UTF-8").content(objectMapper.writeValueAsString(userRequest)))40 .andReturn();41 assertTrue(result.getResponse().getStatus() == MockHttpServletResponse.SC_CREATED);42 verify(createUserServiceMock, times(1)).execute(ArgumentMatchers.refEq(userRequest));43 }44 @Test45 void testCreateInvalidUserReturnBadRequest() throws Exception {46 objectMapper.setSerializationInclusion(Include.NON_NULL);47 var userRequest = aInvalidUserRequest();48 var result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/create-user")49 .contentType("application/json;charset=UTF-8").content(objectMapper.writeValueAsString(userRequest)))50 .andReturn();51 assertTrue(result.getResponse().getStatus() == MockHttpServletResponse.SC_BAD_REQUEST);52 verify(createUserServiceMock, times(0)).execute(ArgumentMatchers.refEq(userRequest));53 }54 @Test55 void testCreateUserThatAlreadyExistsReturnBadRequest() throws Exception {56 objectMapper.setSerializationInclusion(Include.NON_NULL);57 var userRequest = aNormalUserRequest();58 when(createUserServiceMock.execute(any(UserRequest.class)))59 .thenThrow(new ExistingEntityException("user " + userRequest.getName() + " already exists"));60 mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/create-user").contentType("application/json;charset=UTF-8")61 .content(objectMapper.writeValueAsString(userRequest)))62 .andExpect(MockMvcResultMatchers.status().isBadRequest())63 .andExpect(MockMvcResultMatchers.jsonPath("$.error").exists());64 verify(createUserServiceMock, times(1)).execute(ArgumentMatchers.refEq(userRequest));65 }66 @Test67 void testCreateUserAndServiceThrowsRepositoryExceptionShoulReturnFailedDependency() throws Exception {68 objectMapper.setSerializationInclusion(Include.NON_NULL);69 var userRequest = aNormalUserRequest();70 when(createUserServiceMock.execute(any(UserRequest.class))).thenThrow(new RepositoryException("error"));71 mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/create-user").contentType("application/json;charset=UTF-8")72 .content(objectMapper.writeValueAsString(userRequest)))73 .andExpect(MockMvcResultMatchers.status().isFailedDependency())74 .andExpect(MockMvcResultMatchers.jsonPath("$.error").exists());75 verify(createUserServiceMock, times(1)).execute(ArgumentMatchers.refEq(userRequest));76 }77 @Test78 void testCreateUserAndServiceThrowsIOExceptionShoulReturnInternalServerError() throws Exception {79 objectMapper.setSerializationInclusion(Include.NON_NULL);80 var userRequest = aNormalUserRequest();81 when(createUserServiceMock.execute(any(UserRequest.class))).thenThrow(new IOException("error"));82 mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/create-user").contentType("application/json;charset=UTF-8")83 .content(objectMapper.writeValueAsString(userRequest)))84 .andExpect(MockMvcResultMatchers.status().isInternalServerError())85 .andExpect(MockMvcResultMatchers.jsonPath("$.error").exists());86 verify(createUserServiceMock, times(1)).execute(ArgumentMatchers.refEq(userRequest));87 }88 private UserRequest aNormalUserRequest() {89 return new UserRequest("John Smith", "jsmith@gmail.com", "an address 123", "+543675675443", UserType.NORMAL,90 Double.valueOf(0));91 }92 private UserEntity aNormalUserEntity() {93 return new UserEntity("John Smith", "jsmith@gmail.com", "an address 123", "+543675675443", UserType.NORMAL,94 Double.valueOf(0));95 }96 private UserRequest aInvalidUserRequest() {97 return new UserRequest(null, null, "an address 123", "+543675675443", UserType.NORMAL, Double.valueOf(0));98 }99}...
Source:CreateUserUseCaseTest.java
...33 service.execute(aNormalUserRequest());34 } catch (ExistingEntityException e) {35 assertTrue(e instanceof ExistingEntityException);36 assertEquals(e.getMessage(), "user " + mockUserEntity.getName() + " already exists");37 verify(userProviderMock, times(1)).exists(ArgumentMatchers.refEq(mockUserEntity));38 }39 }40 @Test41 public void testCreateUserWhenUserNotExistShoulSaveAndReturn() throws Exception {42 var mockUserEntity = aNormalUserEntity();43 assertNotNull(userProviderMock);44 when(userProviderMock.exists(mockUserEntity)).thenReturn(false);45 when(userProviderMock.save(mockUserEntity)).thenReturn(mockUserEntity);46 CreateUserUseCase service = new CreateUserUseCase(userProviderMock);47 var result = service.execute(aNormalUserRequest());48 assertNotNull(result);49 assertEquals(result, mockUserEntity);50 verify(userProviderMock, times(1)).exists(ArgumentMatchers.refEq(mockUserEntity));51 verify(userProviderMock, times(1)).save(ArgumentMatchers.refEq(mockUserEntity));52 }53 @ParameterizedTest(name = "Run {index}: userEntity={0}, userRequest={1}")54 @MethodSource("testCreateUsersParameters")55 public void testCreateNormalUserMoneyShouldCalculateCorrectGifSaveAndReturn(UserEntity userEntity, UserRequest userRequest)56 throws Throwable {57 assertNotNull(userProviderMock);58 when(userProviderMock.exists(userEntity)).thenReturn(false);59 when(userProviderMock.save(userEntity)).thenReturn(userEntity);60 CreateUserUseCase service = new CreateUserUseCase(userProviderMock);61 var result = service.execute(userRequest);62 assertNotNull(result);63 assertEquals(result, userEntity);64 verify(userProviderMock, times(1)).exists(ArgumentMatchers.refEq(userEntity));65 verify(userProviderMock, times(1)).save(ArgumentMatchers.refEq(userEntity));66 }67 private UserEntity aNormalUserEntity() {68 return new UserEntity("John Smith", "jsmith@gmail.com", "an address 123", "+543675675443", UserType.NORMAL,69 Double.valueOf(0));70 }71 private UserRequest aNormalUserRequest() {72 return new UserRequest("John Smith", "jsmith@gmail.com", "an address 123", "+543675675443", UserType.NORMAL,73 Double.valueOf(0));74 }75 private static UserEntity aUserEntityWithTypeAndMoney(UserType userType, Double money) {76 return new UserEntity("John Smith", "jsmith@gmail.com", "an address 123", "+543675675443", userType, money);77 }78 private static UserRequest aUserRequestWithTypeAndMoney(UserType userType, Double money) {79 return new UserRequest("John Smith", "jsmith@gmail.com", "an address 123", "+543675675443", userType, money);...
Source:ProxyListenerTest.java
...11import java.util.ArrayList;12import java.util.Arrays;13import java.util.List;14import static org.mockito.ArgumentMatchers.any;15import static org.mockito.ArgumentMatchers.refEq;16import static org.mockito.Mockito.reset;17import static org.mockito.Mockito.verify;18import static org.mockito.Mockito.verifyZeroInteractions;19@RunWith(MockitoJUnitRunner.class)20public class ProxyListenerTest {21 @Mock22 private WebElement element1;23 @Mock24 private WebElement element2;25 @Mock26 private WebElement element3;27 @Mock28 private ProxyElementListener listener;29 @Test30 public void testElement() {31 WebElement proxy = LocatorProxies.createWebElement(() -> element1);32 LocatorProxies.addProxyListener(proxy, listener);33 verifyZeroInteractions(listener);34 proxy.click();35 verify(listener).proxyElementSearch(refEq(proxy), any(ElementLocator.class));36 verify(listener).proxyElementFound(refEq(proxy), any(ElementLocator.class), refEq(Arrays.asList(element1)));37 LocatorProxies.removeProxyListener(proxy, listener);38 reset(listener);39 proxy.click();40 verifyZeroInteractions(listener);41 }42 private static class ElementMatcher implements ArgumentMatcher<List<WebElement>> {43 private final List<WebElement> expected;44 ElementMatcher(List<WebElement> expected) {45 this.expected = expected;46 }47 @Override48 public boolean matches(List<WebElement> items) {49 List<WebElement> unwrapped = new ArrayList<>();50 for (WebElement item : items) {51 if (item instanceof WrapsElement) {52 item = ((WrapsElement) item).getWrappedElement();53 }54 unwrapped.add(item);55 }56 return unwrapped.equals(expected);57 }58 }59 @Test60 public void testElementList() {61 List<WebElement> proxy = LocatorProxies.createWebElementList(() -> Arrays.asList(element1, element2, element3));62 LocatorProxies.addProxyListener(proxy, listener);63 verifyZeroInteractions(listener);64 LocatorProxies.now(proxy);65 verify(listener).proxyElementSearch(refEq(proxy), any(ElementLocator.class));66 verify(listener).proxyElementFound(refEq(proxy), any(ElementLocator.class),67 ArgumentMatchers.argThat(new ElementMatcher(Arrays.asList(element1, element2, element3))));68 LocatorProxies.removeProxyListener(proxy, listener);69 reset(listener);70 LocatorProxies.now(proxy);71 verifyZeroInteractions(listener);72 }73}...
Source:FoodServiceTest.java
...15import java.util.Optional;16import static java.util.Arrays.asList;17import static org.junit.Assert.*;18import static org.mockito.ArgumentMatchers.any;19import static org.mockito.ArgumentMatchers.refEq;20import static org.mockito.Mockito.verify;21import static org.mockito.Mockito.verifyNoMoreInteractions;22import static org.mockito.Mockito.when;23@RunWith(MockitoJUnitRunner.class)24public class FoodServiceTest {25 @InjectMocks26 private FoodService foodService;27 @Mock28 private FoodRepository foodRepository;29 @Mock30 private FoodMapper foodMapper;31 @Test32 public void addFoodToGlobalList() {33 Food food = new Food(1L, "Food", 120L, 12L, 5L, 28L);34 when(foodRepository.findById(1L)).thenReturn(Optional.of(food));35 foodService.addFoodToGlobalList(food);36 //verify(foodRepository).findById(1L);37 verify(foodRepository).save(refEq(new Food(1L, "Food", 120L, 12L, 5L, 28L)));38 verifyNoMoreInteractions(foodRepository);39 }40 @Test41 public void editFood(){42 Food food = new Food(1L, "Food", 120L, 12L, 5L, 28L);43 when(foodRepository.findById(1L)).thenReturn(Optional.of(food));44 foodService.addFoodToGlobalList(food);45 FoodDto foodDto = new FoodDto( "Food", 220L, 22L, 15L, 128L);46 when(foodMapper.toFood(foodDto)).thenReturn(new Food(1L, "Food", 220L, 22L, 15L, 128L));47 foodService.editFood(1L, foodDto);48 verify(foodRepository).save(refEq(new Food(1L, "Food", 220L, 22L, 15L, 128L)));49 verifyNoMoreInteractions(foodRepository);50 }51 @Test52 public void delete() {53 foodService.delete(1L);54 verify(foodRepository).deleteById(1L);55 verifyNoMoreInteractions(foodRepository);56 }57}...
Source:GroupServiceImplTest.java
...24// GroupEntity group2 = new GroupEntity().builder().gno(2L).title("title2").build();25// MemberEntity member1 = new MemberEntity().builder().email("email1").password("password1").build();26// MemberEntity member2 = new MemberEntity().builder().email("email2").password("password2").build();27// MemberEntity member3 = new MemberEntity().builder().email("email3").password("password3").build();28// when(positionRepo.findByMemberEntity(ArgumentMatchers.refEq(member1))).thenReturn(Optional.empty());29// when(positionRepo.findByMemberEntity(ArgumentMatchers.refEq(member2))).thenReturn(30// Optional.of(31// new PositionEntity().builder().32// group(group2).33// member(member2).34// whichPosition(WhichPosition.Leader).build()35// )36// );37// when(positionRepo.findByMemberEntity(ArgumentMatchers.refEq(member3))).thenReturn(38// Optional.of(39// new PositionEntity().builder().40// group(group1).41// member(member3).42// whichPosition(WhichPosition.Follower).build()43// )44// );45// assertFalse(groupService.dismissGroupManual(1L, member1));46// assertFalse(groupService.dismissGroupManual(1L, member3));47// assertFalse(groupService.dismissGroupManual(2L, member3));48// assertFalse(groupService.dismissGroupManual(1L, member2));49// assertTrue(groupService.dismissGroupManual(2L, member2));50 }51 ...
refEq
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.refEq;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.ArrayList;5import java.util.List;6public class Example1 {7 public static void main(String[] args) {8 List<String> mockedList = mock(ArrayList.class);9 mockedList.add("one");10 verify(mockedList).add(refEq("one"));11 }12}
refEq
Using AI Code Generation
1package com.automationrhapsody.junit;2import static org.mockito.ArgumentMatchers.refEq;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.when;6import java.util.HashMap;7import java.util.Map;8import org.junit.Test;9public class MockitoRefEqTest {10 public void testRefEq() {11 Map<String, String> map = new HashMap<>();12 map.put("key1", "value1");13 map.put("key2", "value2");14 Map<String, String> mapMock = mock(Map.class);15 when(mapMock.get(refEq(map))).thenReturn("value1");16 String value = mapMock.get(map);17 System.out.println(value);18 verify(mapMock).get(refEq(map));19 }20}
refEq
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.*;2import static org.mockito.Mockito.*;3import org.mockito.*;4import org.mockito.stubbing.*;5import org.mockito.invocation.*;6import org.mockito.exceptions.misusing.*;7import org.mockito.exceptions.verification.*;8import org.mockito.exceptions.base.*;9import org.mockito.exceptions.reporting.*;10import org.mockito.internal.*;11import org.mockito.internal.invocation.*;12import org.mockito.internal.invocation.finder.*;13import org.mockito.internal.invocation.realmethod.*;14import org.mockito.internal.invocation.realmethod.RealMethod.*;15import org.mockito.internal.progress.*;16import org.mockito.internal.progress.ThreadSafeMockingProgress.*;17import org.mockito.internal.stubbing.*;18import org.mockito.internal.stubbing.defaultanswers.*;19import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues.*;20import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues.*;21import org.mockito.internal.stubbing.defaultanswers.ReturnsMocks.*;22import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls.*;23import org.mockito.internal.stubbing.defaultanswers.ReturnsSubclasses.*;24import org.mockito.internal.stubbing.defaultanswers.ReturnsTypifiedValues.*;25import org.mockito.internal.stubbing.defaultanswers.ReturnsValues.*;26import org.mockito.internal.stubbing.defaultanswers.ThrowsException.*;27import org.mockito.internal.stubbing.defaultanswers.ThrowsExceptions.*;28import org.mockito.internal.stubbing.defaultanswers.*;29import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues.*;30import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues.*;31import org.mockito.internal.stubbing.defaultanswers.ReturnsMocks.*;32import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls.*;33import org.mockito.internal.stubbing.defaultanswers.ReturnsSubclasses.*;34import org.mockito.internal.stubbing.defaultanswers.ReturnsTypifiedValues.*;35import org.mockito.internal.stubbing.defaultanswers.ReturnsValues.*;36import org.mockito.internal.stubbing.defaultanswers.ThrowsException.*;37import org.mockito.internal.stubbing.defaultanswers.ThrowsExceptions.*;38import org.mockito.internal.stubbing.defaultanswers.*;39import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues.*;40import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues.*;41import org.mockito.internal.stubbing.defaultanswers.ReturnsMocks.*;42import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls.*;43import org.mockito.internal.stubbing.defaultanswers.ReturnsSubclasses.*;44import org.mockito.internal.stubbing.defaultanswers.ReturnsTypifiedValues.*;45import org.mockito.internal.stubbing.defaultanswers.ReturnsValues.*;46import org.mockito.internal.stubbing.defaultanswers.ThrowsException.*;47import org.mockito.internal.stubbing.defaultanswers.ThrowsExceptions.*;48import org.mockito.internal.stubbing.defaultanswers
refEq
Using AI Code Generation
1package com.automationrhapsody.junit;2import static org.junit.Assert.*;3import static org.mockito.Mockito.*;4import org.junit.Test;5public class MockitoRefEqTest {6 public void testRefEq() {7 Person person = new Person("John", "Doe");8 PersonDao personDao = mock(PersonDao.class);9 personDao.save(person);10 verify(personDao).save(refEq(person));11 }12}13package com.automationrhapsody.junit;14import static org.junit.Assert.*;15import static org.mockito.Mockito.*;16import org.junit.Test;17public class MockitoRefEqTest {18 public void testRefEq() {19 Person person = new Person("John", "Doe");20 PersonDao personDao = mock(PersonDao.class);21 personDao.save(person);22 verify(personDao).save(refEq(person));23 }24}25package com.automationrhapsody.junit;26import static org.junit.Assert.*;27import static org.mockito.Mockito.*;28import org.junit.Test;29public class MockitoRefEqTest {30 public void testRefEq() {31 Person person = new Person("John", "Doe");32 PersonDao personDao = mock(PersonDao.class);33 personDao.save(person);34 verify(personDao).save(refEq(person));35 }36}37package com.automationrhapsody.junit;38import static org.junit.Assert.*;39import static org.mockito.Mockito.*;40import org.junit.Test;41public class MockitoRefEqTest {42 public void testRefEq() {43 Person person = new Person("John", "Doe");44 PersonDao personDao = mock(PersonDao.class);45 personDao.save(person);46 verify(personDao).save(refEq(person));47 }48}49package com.automationrhapsody.junit;50import static org.junit.Assert.*;51import static org.mockito.Mockito.*;52import org.junit.Test;53public class MockitoRefEqTest {54 public void testRefEq() {55 Person person = new Person("John", "Doe");
refEq
Using AI Code Generation
1import static org.mockito.Mockito.*;2import java.util.ArrayList;3import java.util.List;4public class MockitoRefEqExample {5 public static void main(String[] args) {6 List mock = mock(List.class);7 mock.add("Test");8 verify(mock).add(refEq("Test"));9 verify(mock).add(refEq(new ArrayList()));10 }11}12org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:13mock.add(14 refEq(15);16-> at MockitoRefEqExample.main(MockitoRefEqExample.java:23)17mock.add(18 refEq(19);20-> at MockitoRefEqExample.main(MockitoRefEqExample.java:18)21import static org.mockito.Mockito.*;22import java.util.ArrayList;23import java.util.List;24public class MockitoRefEqExample {25 public static void main(String[] args) {26 List mock = mock(List.class);27 mock.add("Test");28 verify(mock).add(refEq("Test"));29 verify(mock).add(refEq(new ArrayList(), "ignore"));30 }31}32org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:33mock.add(34 refEq(35);36-> at MockitoRefEqExample.main(MockitoRefEqExample.java:23)37mock.add(38 refEq(39);40-> at MockitoRefEqExample.main(MockitoRefEqExample.java:18)41import static org.mockito.Mockito.*;42import java.util.ArrayList;43import java.util.List;44public class MockitoRefEqExample {45 public static void main(String[] args) {46 List mock = mock(List.class);47 mock.add("Test");48 verify(mock).add(refEq("Test"));
refEq
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.refEq;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4public class Test1 {5 public static void main(String[] args) {6 EmployeeDAO employeeDAO = mock(EmployeeDAO.class);7 Employee employee = new Employee(1, "John", "Doe", "
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!!