Best Mockito code snippet using org.mockito.Mockito.atMostOnce
Source:UpgradeJudgementTest.java
...40import java.util.Iterator;41import java.util.concurrent.TimeUnit;42import static org.junit.Assert.assertFalse;43import static org.junit.Assert.assertTrue;44import static org.mockito.Mockito.atMostOnce;45import static org.mockito.Mockito.never;46import static org.mockito.Mockito.verify;47import static org.mockito.Mockito.when;48@RunWith(MockitoJUnitRunner.class)49public class UpgradeJudgementTest {50 51 private final long sleepForCheck = 800L;52 53 @Mock54 private ConfigurableApplicationContext context;55 56 @Mock57 private RaftPeerSet raftPeerSet;58 59 @Mock60 private RaftCore raftCore;61 62 @Mock63 private ClusterVersionJudgement versionJudgement;64 65 @Mock66 private ServerMemberManager memberManager;67 68 @Mock69 private ServiceManager serviceManager;70 71 @Mock72 private DoubleWriteDelayTaskEngine doubleWriteDelayTaskEngine;73 74 @Mock75 private UpgradeStates upgradeStates;76 77 @Mock78 private ServiceStorage serviceStorage;79 80 private UpgradeJudgement upgradeJudgement;81 82 @Before83 public void setUp() throws Exception {84 EnvUtil.setEnvironment(new MockEnvironment());85 EnvUtil.setIsStandalone(false);86 when(context.getBean(ServiceManager.class)).thenReturn(serviceManager);87 when(context.getBean(ServiceStorage.class)).thenReturn(serviceStorage);88 ApplicationUtils.injectContext(context);89 upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager,90 upgradeStates, doubleWriteDelayTaskEngine);91 }92 93 @After94 public void tearDown() {95 upgradeJudgement.shutdown();96 EnvUtil.setEnvironment(null);97 }98 99 @Test100 public void testUpgradeOneNode() throws Exception {101 Collection<Member> members = mockMember("1.3.2", "1.3.2", "2.0.0");102 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());103 verify(raftPeerSet, never()).init();104 verify(raftCore, never()).init();105 verify(versionJudgement, never()).reset();106 TimeUnit.MILLISECONDS.sleep(sleepForCheck);107 assertFalse(upgradeJudgement.isUseGrpcFeatures());108 assertFalse(upgradeJudgement.isUseJraftFeatures());109 }110 111 @Test112 public void testUpgradeOneFor14XNode() throws Exception {113 Collection<Member> members = mockMember("1.4.0", "2.0.0", "2.0.0");114 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());115 verify(raftPeerSet, never()).init();116 verify(raftCore, never()).init();117 verify(versionJudgement, never()).reset();118 TimeUnit.MILLISECONDS.sleep(sleepForCheck);119 assertFalse(upgradeJudgement.isUseGrpcFeatures());120 assertTrue(upgradeJudgement.isUseJraftFeatures());121 }122 123 @Test124 public void testUpgradeTwoNode() throws Exception {125 Collection<Member> members = mockMember("", "2.0.0", "2.0.0");126 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());127 verify(raftPeerSet, never()).init();128 verify(raftCore, never()).init();129 verify(versionJudgement, never()).reset();130 TimeUnit.MILLISECONDS.sleep(sleepForCheck);131 assertFalse(upgradeJudgement.isUseGrpcFeatures());132 assertFalse(upgradeJudgement.isUseJraftFeatures());133 }134 135 @Test136 public void testUpgradeCheckSucc() throws Exception {137 Collection<Member> members = mockMember("2.0.0-snapshot", "2.0.0", "2.0.0");138 Iterator<Member> iterator = members.iterator();139 when(doubleWriteDelayTaskEngine.isEmpty()).thenReturn(true);140 iterator.next();141 while (iterator.hasNext()) {142 iterator.next().setExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE, true);143 }144 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());145 verify(raftPeerSet, never()).init();146 verify(raftCore, never()).init();147 verify(versionJudgement, never()).reset();148 TimeUnit.MILLISECONDS.sleep(sleepForCheck);149 assertTrue(upgradeJudgement.isUseGrpcFeatures());150 assertTrue(upgradeJudgement.isUseJraftFeatures());151 }152 153 @Test154 public void testUpgradeCheckSelfFail() throws Exception {155 Collection<Member> members = mockMember("2.0.0", "2.0.0", "2.0.0");156 Iterator<Member> iterator = members.iterator();157 when(doubleWriteDelayTaskEngine.isEmpty()).thenReturn(false);158 iterator.next();159 while (iterator.hasNext()) {160 iterator.next().setExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE, true);161 }162 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());163 verify(raftPeerSet, never()).init();164 verify(raftCore, never()).init();165 verify(versionJudgement, never()).reset();166 TimeUnit.MILLISECONDS.sleep(sleepForCheck);167 assertFalse(upgradeJudgement.isUseGrpcFeatures());168 assertFalse(upgradeJudgement.isUseJraftFeatures());169 }170 171 @Test172 public void testAlreadyUpgradedAndCheckSelfFail() throws Exception {173 Collection<Member> members = mockMember("2.0.0", "2.0.0", "2.0.0");174 Iterator<Member> iterator = members.iterator();175 iterator.next();176 while (iterator.hasNext()) {177 iterator.next().setExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE, true);178 }179 when(upgradeStates.isUpgraded()).thenReturn(true);180 upgradeJudgement.shutdown();181 upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager,182 upgradeStates, doubleWriteDelayTaskEngine);183 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());184 verify(raftPeerSet, never()).init();185 verify(raftCore, never()).init();186 verify(versionJudgement, never()).reset();187 TimeUnit.MILLISECONDS.sleep(sleepForCheck);188 assertTrue(upgradeJudgement.isUseGrpcFeatures());189 assertTrue(upgradeJudgement.isUseJraftFeatures());190 }191 192 @Test193 public void testUpgradeCheckOthersFail() throws Exception {194 Collection<Member> members = mockMember("2.0.0", "2.0.0", "2.0.0");195 when(doubleWriteDelayTaskEngine.isEmpty()).thenReturn(true);196 members.iterator().next().setExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE, true);197 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());198 verify(raftPeerSet, never()).init();199 verify(raftCore, never()).init();200 verify(versionJudgement, never()).reset();201 TimeUnit.MILLISECONDS.sleep(sleepForCheck);202 assertFalse(upgradeJudgement.isUseGrpcFeatures());203 assertFalse(upgradeJudgement.isUseJraftFeatures());204 }205 206 @Test207 public void testAlreadyUpgradedAndCheckOthersFail() throws Exception {208 Collection<Member> members = mockMember("2.0.0", "2.0.0", "2.0.0");209 members.iterator().next().setExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE, true);210 upgradeJudgement.shutdown();211 when(upgradeStates.isUpgraded()).thenReturn(true);212 upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager,213 upgradeStates, doubleWriteDelayTaskEngine);214 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());215 TimeUnit.MILLISECONDS.sleep(sleepForCheck);216 verify(raftPeerSet, never()).init();217 verify(raftCore, never()).init();218 verify(versionJudgement, never()).reset();219 assertTrue(upgradeJudgement.isUseGrpcFeatures());220 assertTrue(upgradeJudgement.isUseJraftFeatures());221 }222 223 @Test224 public void testDowngradeOneFor14XNode() throws Exception {225 upgradeJudgement.setUseGrpcFeatures(true);226 upgradeJudgement.setUseJraftFeatures(true);227 Collection<Member> members = mockMember("1.4.0", "2.0.0", "2.0.0");228 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());229 verify(raftPeerSet, never()).init();230 verify(raftCore, never()).init();231 verify(versionJudgement, never()).reset();232 TimeUnit.MILLISECONDS.sleep(sleepForCheck);233 assertFalse(upgradeJudgement.isUseGrpcFeatures());234 assertTrue(upgradeJudgement.isUseJraftFeatures());235 }236 237 @Test238 public void testAlreadyUpgradedAndDowngradeOneFor14XNode() throws Exception {239 when(upgradeStates.isUpgraded()).thenReturn(true);240 upgradeJudgement.shutdown();241 upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager,242 upgradeStates, doubleWriteDelayTaskEngine);243 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(mockMember("1.4.0", "2.0.0", "2.0.0")).build());244 verify(raftPeerSet, never()).init();245 verify(raftCore, never()).init();246 verify(versionJudgement, never()).reset();247 TimeUnit.MILLISECONDS.sleep(sleepForCheck);248 assertFalse(upgradeJudgement.isUseGrpcFeatures());249 assertTrue(upgradeJudgement.isUseJraftFeatures());250 }251 252 @Test253 public void testDowngradeTwoNode() throws Exception {254 upgradeJudgement.setUseGrpcFeatures(true);255 upgradeJudgement.setUseJraftFeatures(true);256 Collection<Member> members = mockMember("", "", "2.0.0");257 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());258 verify(raftPeerSet, atMostOnce()).init();259 verify(raftCore, atMostOnce()).init();260 verify(versionJudgement, atMostOnce()).reset();261 TimeUnit.MILLISECONDS.sleep(sleepForCheck);262 assertFalse(upgradeJudgement.isUseGrpcFeatures());263 assertFalse(upgradeJudgement.isUseJraftFeatures());264 }265 266 @Test267 public void testAlreadyUpgradedAndDowngradeTwoNode() throws Exception {268 when(upgradeStates.isUpgraded()).thenReturn(true);269 upgradeJudgement.shutdown();270 upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager,271 upgradeStates, doubleWriteDelayTaskEngine);272 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(mockMember("", "", "2.0.0")).build());273 verify(raftPeerSet, atMostOnce()).init();274 verify(raftCore, atMostOnce()).init();275 verify(versionJudgement, atMostOnce()).reset();276 TimeUnit.MILLISECONDS.sleep(sleepForCheck);277 assertFalse(upgradeJudgement.isUseGrpcFeatures());278 assertFalse(upgradeJudgement.isUseJraftFeatures());279 }280 281 @Test282 public void testDowngradeOneNode() throws Exception {283 upgradeJudgement.setUseGrpcFeatures(true);284 upgradeJudgement.setUseJraftFeatures(true);285 Collection<Member> members = mockMember("1.3.2", "2.0.0", "2.0.0");286 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(members).build());287 verify(raftPeerSet, atMostOnce()).init();288 verify(raftCore, atMostOnce()).init();289 verify(versionJudgement, atMostOnce()).reset();290 TimeUnit.MILLISECONDS.sleep(sleepForCheck);291 assertFalse(upgradeJudgement.isUseGrpcFeatures());292 assertFalse(upgradeJudgement.isUseJraftFeatures());293 }294 295 @Test296 public void testAlreadyUpgradedAndDowngradeOneNode() throws Exception {297 when(upgradeStates.isUpgraded()).thenReturn(true);298 upgradeJudgement.shutdown();299 upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager,300 upgradeStates, doubleWriteDelayTaskEngine);301 upgradeJudgement.onEvent(MembersChangeEvent.builder().triggers(mockMember("1.3.2", "2.0.0", "2.0.0")).build());302 verify(raftPeerSet, atMostOnce()).init();303 verify(raftCore, atMostOnce()).init();304 verify(versionJudgement, atMostOnce()).reset();305 TimeUnit.MILLISECONDS.sleep(sleepForCheck);306 assertFalse(upgradeJudgement.isUseGrpcFeatures());307 assertFalse(upgradeJudgement.isUseJraftFeatures());308 }309 310 @Test311 public void testUpgradedBySpecifiedSelfUpgradeChecker() throws InterruptedException {312 upgradeJudgement.shutdown();313 MockEnvironment mockEnvironment = new MockEnvironment();314 mockEnvironment.setProperty("upgrading.checker.type", "mock");315 EnvUtil.setEnvironment(mockEnvironment);316 mockMember("1.3.2", "2.0.0", "2.0.0");317 upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager,318 upgradeStates, doubleWriteDelayTaskEngine);...
Source:ConfirmationServiceTests.java
...20import static org.assertj.core.api.Assertions.assertThat;21import static org.assertj.core.api.Assertions.assertThatThrownBy;22import static org.mockito.ArgumentMatchers.any;23import static org.mockito.ArgumentMatchers.eq;24import static org.mockito.Mockito.atMostOnce;25import static org.mockito.Mockito.doAnswer;26import static org.mockito.Mockito.doReturn;27import static org.mockito.Mockito.never;28import static org.mockito.Mockito.verify;29import static org.ssor.boss.core.entity.ConfirmationType.USER_CONFIRMATION;30@ExtendWith(MockitoExtension.class)31public class ConfirmationServiceTests32{33 @Mock34 static ConfirmationRepository confirmationRepository;35 static ConfirmationService confirmationService;36 static List<Confirmation> mockConfirmations;37 static ConfirmationType TYPE_ID = USER_CONFIRMATION;38 static String HASH1 = UUID.randomUUID().toString();39 static String HASH2 = UUID.randomUUID().toString();40 static long GOOD_UNTIL = Instant.now().plusSeconds(60 * 60 * 24).toEpochMilli();41 static long EXPIRED = Instant.now().minusSeconds(60 * 60 * 24).toEpochMilli();42 @BeforeEach43 void setUp()44 {45 final var confirmation1 = new Confirmation(1, TYPE_ID, 165432476, HASH1, GOOD_UNTIL);46 final var confirmation2 = new Confirmation(2, TYPE_ID, 789843544, HASH2, EXPIRED);47 mockConfirmations = Lists.newArrayList(confirmation1, confirmation2);48 confirmationService = new ConfirmationService(confirmationRepository);49 assertThat(confirmationService).isNotNull();50 }51 @AfterEach52 void tearDown()53 {54 mockConfirmations = null;55 confirmationService = null;56 }57 @Test58 void test_GenerateConfirmation_GeneratesAConfirmationEntrySuccessfully()59 {60 // Just mock the result.61 final var hash = UUID.randomUUID().toString();62 final var generationResult = new Confirmation(3, USER_CONFIRMATION, 238343, hash, 0);63 doReturn(generationResult).when(confirmationRepository).save(any());64 final var result = confirmationService.generateConfirmation(USER_CONFIRMATION, 238343);65 verify(confirmationRepository, atMostOnce()).save(any());66 assertThat(result.getId()).isEqualTo(3);67 assertThat(result.getConfirmationHash()).isNotBlank();68 assertThat(result.getGoodUntil()).isNotNull();69 }70 @Test71 void test_Confirm_ConfirmsEntrySuccessfully()72 {73 final var confirmation = mockConfirmations.get(0);74 doReturn(Optional.of(confirmation)).when(confirmationRepository).findByConfirmationHash(eq(HASH1));75 doAnswer(invocationOnMock -> mockConfirmations.remove(confirmation)).when(confirmationRepository).delete(any());76 final var now = Instant.now().toEpochMilli();77 assertThat(confirmation.getGoodUntil()).isGreaterThan(now);78 final var result = confirmationService.confirm(HASH1);79 verify(confirmationRepository, atMostOnce()).findByConfirmationHash(HASH1);80 verify(confirmationRepository, atMostOnce()).delete(any());81 assertThat(result).isEqualTo(165432476); // User id.82 }83 @Test84 void test_ConfirmProducesInvalidConfirmationException_WhenConfirmationCodeInvalid()85 {86 doReturn(Optional.empty()).when(confirmationRepository).findByConfirmationHash(any());87 assertThatThrownBy(() -> confirmationService.confirm("asdf")).isInstanceOf(InvalidConfirmationException.class)88 .hasMessage("Confirmation doesn't exist");89 verify(confirmationRepository, atMostOnce()).findByConfirmationHash(any());90 verify(confirmationRepository, never()).delete(any());91 }92 @Test93 void test_ConfirmProducesInvalidConfirmationException_WhenConfirmationExpired()94 {95 final var confirmation = mockConfirmations.get(1);96 doReturn(Optional.of(confirmation)).when(confirmationRepository).findByConfirmationHash(eq(HASH2));97 assertThatThrownBy(() -> confirmationService.confirm(HASH2)).isInstanceOf(InvalidConfirmationException.class)98 .hasMessage("Confirmation is expired");99 verify(confirmationRepository, atMostOnce()).findByConfirmationHash(HASH2);100 verify(confirmationRepository, never()).delete(any());101 }102}...
Source:AtMostXVerificationTest.java
...7import static org.junit.Assert.assertEquals;8import static org.junit.Assert.fail;9import static org.mockito.Mockito.anyString;10import static org.mockito.Mockito.atMost;11import static org.mockito.Mockito.atMostOnce;12import static org.mockito.Mockito.inOrder;13import static org.mockito.Mockito.verify;14import static org.mockito.Mockito.verifyNoMoreInteractions;15import java.util.List;16import org.junit.Test;17import org.mockito.InOrder;18import org.mockito.Mock;19import org.mockito.exceptions.base.MockitoException;20import org.mockito.exceptions.verification.MoreThanAllowedActualInvocations;21import org.mockito.exceptions.verification.NoInteractionsWanted;22import org.mockito.verification.VerificationMode;23import org.mockitoutil.TestBase;24public class AtMostXVerificationTest extends TestBase {25 @Mock private List<String> mock;26 @Test27 public void shouldVerifyAtMostXTimes() throws Exception {28 mock.clear();29 mock.clear();30 verify(mock, atMost(2)).clear();31 verify(mock, atMost(3)).clear();32 try {33 verify(mock, atMostOnce()).clear();34 fail();35 } catch (MoreThanAllowedActualInvocations e) {36 }37 }38 @Test39 public void shouldWorkWithArgumentMatchers() throws Exception {40 mock.add("one");41 verify(mock, atMost(5)).add(anyString());42 try {43 verify(mock, atMost(0)).add(anyString());44 fail();45 } catch (MoreThanAllowedActualInvocations e) {46 }47 }48 @Test49 public void shouldNotAllowNegativeNumber() throws Exception {50 try {51 verify(mock, atMost(-1)).clear();52 fail();53 } catch (MockitoException e) {54 assertEquals("Negative value is not allowed here", e.getMessage());55 }56 }57 @Test58 public void shouldPrintDecentMessage() throws Exception {59 mock.clear();60 mock.clear();61 try {62 verify(mock, atMostOnce()).clear();63 fail();64 } catch (MoreThanAllowedActualInvocations e) {65 assertEquals("\nWanted at most 1 time but was 2", e.getMessage());66 }67 }68 @Test69 public void shouldNotAllowInOrderMode() throws Exception {70 mock.clear();71 InOrder inOrder = inOrder(mock);72 try {73 inOrder.verify(mock, atMostOnce()).clear();74 fail();75 } catch (MockitoException e) {76 assertEquals("AtMost is not implemented to work with InOrder", e.getMessage());77 }78 }79 @Test80 public void shouldMarkInteractionsAsVerified() throws Exception {81 mock.clear();82 mock.clear();83 verify(mock, atMost(3)).clear();84 verifyNoMoreInteractions(mock);85 }86 @Test87 public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exception {...
Source:PersonServiceImplTest.java
...45 public void create() {46 PersonEntity person = newPerson();47 Mockito.when(personRepository.save(person)).thenReturn(person);48 personService.create(person);49 Mockito.verify(personService, Mockito.atMostOnce()).create(person);50 }51 @Test(expected = ResponseException.class)52 public void createNull() {53 personService.create(null);54 Mockito.verify(personService, Mockito.atMostOnce()).create(null);55 }56 @Test57 public void update() {58 PersonEntity person = newPerson();59 Mockito.when(personRepository.save(person)).thenReturn(person);60 personService.update(person);61 Mockito.verify(personService, Mockito.atMostOnce()).update(person);62 }63 @Test(expected = ResponseException.class)64 public void updateNull() {65 personService.update(null);66 Mockito.verify(personService, Mockito.atMostOnce()).update(null);67 }68 @Test69 public void delete() {70 Optional<PersonEntity> response = Optional.of(newPerson());71 Mockito.when(personRepository.findById((long) 1)).thenReturn(response);72 Mockito.doNothing().when(personRepository).delete(response.get());73 personService.delete((long) 1);74 Mockito.verify(personService, Mockito.atMostOnce()).delete((long) 1);75 }76 @Test(expected = ResponseException.class)77 public void deleteThrowsException() {78 Optional<PersonEntity> response = Optional.of(newPerson());79 Mockito.when(personRepository.findById((long) 0)).thenThrow(new ResponseException("Delete exception"));80 personService.delete((long) 0);81 Mockito.verify(personService, Mockito.atMostOnce()).delete((long) 0);82 }83 public PersonEntity newPerson() {84 return new PersonEntity(1l, 12345678999l, "name");85 }86}...
Source:UserServiceImplJavaTest.java
...33 public void create() {34 User user = newUser();35 Mockito.when(userRepository.save(user)).thenReturn(user);36 userService.create(user);37 Mockito.verify(userService, Mockito.atMostOnce()).create(user);38 }39 @Test(expected = ResponseException.class)40 public void createNull() {41 Mockito.when(userRepository.save(null)).thenReturn(null);42 userService.create(null);43 Mockito.verify(userService, Mockito.atMostOnce()).create(null);44 }45 @Test(expected = ResponseException.class)46 public void createExistingUser() {47 User user = newUser();48 Optional<User> response = Optional.of(user);49 Mockito.when(userRepository.findByUsername("username")).thenReturn(response);50 userService.create(user);51 Mockito.verify(userService, Mockito.atMostOnce()).create(user);52 }53 @Test54 public void update() {55 User user = newUser();56 Mockito.when(userRepository.save(user)).thenReturn(user);57 userService.update(user);58 Mockito.verify(userService, Mockito.atMostOnce()).update(user);59 }60 @Test(expected = ResponseException.class)61 public void updateNull() {62 Mockito.when(userRepository.save(null)).thenReturn(null);63 userService.update(null);64 Mockito.verify(userService, Mockito.atMostOnce()).update(null);65 }66 @Test67 public void delete() {68 Optional<User> response = Optional.of(new User());69 Mockito.when(userRepository.findByUsername("username")).thenReturn(response);70 Mockito.doNothing().when(userRepository).delete(response.get());71 userService.delete("username");72 Mockito.verify(userService, Mockito.atMostOnce()).delete("username");73 }74 @Test(expected = ResponseException.class)75 public void deleteThrowsException() {76 Optional<User> response = Optional.of(new User());77 Mockito.when(userRepository.findByUsername("")).thenThrow(new ResponseException("Delete exception"));78 Mockito.doNothing().when(userRepository).delete(response.get());79 userService.delete("");80 Mockito.verify(userService, Mockito.atMostOnce()).delete("");81 }82 public User newUser() {83 return new User("username", "password");84 }85}...
Source:TablePKRepoH2ImplTest.java
1package ru.treshchilin.training.h2jdbcsample.dao.impl;2import static org.assertj.core.api.Assertions.assertThat;3import static org.mockito.Mockito.atMost;4import static org.mockito.Mockito.atMostOnce;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.verify;7import static org.mockito.Mockito.when;8import java.sql.Connection;9import java.sql.PreparedStatement;10import java.sql.ResultSet;11import java.sql.Statement;12import java.util.List;13import org.junit.jupiter.api.Test;14import org.junit.jupiter.api.extension.ExtendWith;15import org.mockito.InjectMocks;16import org.mockito.Mock;17import org.mockito.junit.jupiter.MockitoExtension;18import ru.treshchilin.training.h2jdbcsample.model.TablePkDescription;19@ExtendWith(MockitoExtension.class)20class TablePKRepoH2ImplTest {21 22 private final String SELECT_ALL_FROM_TABLE_LIST = "SELECT * FROM TABLE_LIST";23 private final String SELECT_ALL_FROM_TABLE_COLS = "SELECT COLUMN_TYPE FROM TABLE_COLS WHERE TABLE_NAME=? AND lower(COLUMN_NAME)=lower(?)";24 25 private final String TABLE_NAME = "TABLE_NAME";26 private final String COLUMN_TYPE = "COLUMN_TYPE";27 private final String PK = "PK";28 @Mock29 Connection connection;30 31 @InjectMocks32 TablePKRepoH2Impl underTest;33 34 @Test35 void test() {36 assertThat(underTest).isNotNull();37 }38 39 @Test40 void close() throws Exception {41 underTest.close();42 43 verify(connection, atMostOnce()).close();44 }45 46 @Test47 void findAll() throws Exception {48// Given49 ResultSet tableListRs = mock(ResultSet.class);50 when(tableListRs.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);51 when(tableListRs.getString(TABLE_NAME)).thenReturn("users").thenReturn("accounts").thenReturn("not_a_table");52 when(tableListRs.getString(PK)).thenReturn("ID").thenReturn("account, account_id").thenReturn("");53 54 Statement tableListStatement = mock(Statement.class);55 when(tableListStatement.executeQuery(SELECT_ALL_FROM_TABLE_LIST)).thenReturn(tableListRs);56 57 when(connection.createStatement()).thenReturn(tableListStatement);58 59 ResultSet pkTypeRs = mock(ResultSet.class);60 when(pkTypeRs.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);61 when(pkTypeRs.getString(COLUMN_TYPE)).thenReturn("INT").thenReturn("VARCHAR(32)").thenReturn("INT");62 63 PreparedStatement preparedStatement = mock(PreparedStatement.class);64 when(preparedStatement.executeQuery()).thenReturn(pkTypeRs);65 66 when(connection.prepareStatement(SELECT_ALL_FROM_TABLE_COLS)).thenReturn(preparedStatement);67 68// When69 List<TablePkDescription> underTestReturns = underTest.findAll();70 71 72// Then73 assertThat(underTestReturns.size()).isEqualTo(3);74 75 verify(tableListRs, atMostOnce()).close();76 verify(pkTypeRs, atMost(4)).close();77 78 verify(tableListStatement, atMostOnce()).close();79 verify(preparedStatement, atMostOnce()).close();80 }81}...
Source:FileServiceTest.java
...22 private FileService fileService;23 @Test24 void getFilesByUser() {25 fileService.getFilesByUser(1);26 verify(mock_fileMapper, atMostOnce()).getFilesByUser(1);27 }28 @Test29 void getFileById() {30 fileService.getFileById(1);31 verify(mock_fileMapper, atMostOnce()).getFileById(1);32 }33 @Test34 void addFile() throws IOException {35 MockMultipartFile multipartFile = new MockMultipartFile(36 "SomeFile", null, null, (byte[]) null37 );38 File file = new File();39 String username = "user";40 when(mock_userService.getUser(username).getUserId()).thenReturn(1);41 fileService.addFile(multipartFile, username);42 verify(mock_userService, atMostOnce()).getUser(username).getUserId();43 verify(mock_fileMapper, atMostOnce()).insertFile(file);44 }45 @Test46 void getAllFiles() {47 fileService.getAllFiles();48 verify(mock_fileMapper, atMostOnce()).getAllFiles();49 }50 @Test51 void test_deleteFile_sad_path() {52 fileService.deleteFile(1);53 verify(mock_fileMapper).getFileById(1);54 }55 @Test56 void test_deleteFile_happy_path() {57 when(mock_fileMapper.getFileById(1)).thenReturn(new File());58 fileService.deleteFile(1);59 verify(mock_fileMapper).getFileById(1);60 verify(mock_fileMapper).deleteFile(1);61 }62}...
Source:FileSaveDestinationTest.java
1package ru.treshchilin.training.h2jdbcsample.save.impl;2import static org.assertj.core.api.Assertions.assertThat;3import static org.mockito.Mockito.atMostOnce;4import static org.mockito.Mockito.verify;5import java.io.BufferedWriter;6import java.io.IOException;7import org.junit.jupiter.api.Test;8import org.junit.jupiter.api.extension.ExtendWith;9import org.mockito.InjectMocks;10import org.mockito.Mock;11import org.mockito.junit.jupiter.MockitoExtension;12@ExtendWith(MockitoExtension.class)13class FileSaveDestinationTest {14 @Mock15 BufferedWriter bufferedWriter;16 17 @InjectMocks18 FileSaveDestination underTest;19 20 @Test21 void test() {22 assertThat(underTest).isNotNull();23 }24 25 @Test26 void save() throws IOException {27 String str = "to save";28 29 underTest.save(str);30 31 verify(bufferedWriter, atMostOnce()).append(str);32 verify(bufferedWriter, atMostOnce()).flush();33 }34 35 @Test36 void close() throws IOException {37 underTest.close();38 39 verify(bufferedWriter, atMostOnce()).close();40 }41}...
atMostOnce
Using AI Code Generation
1package com.ack.j2se.mock;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mock;5import org.mockito.runners.MockitoJUnitRunner;6import static org.mockito.Mockito.atMostOnce;7import static org.mockito.Mockito.times;8import static org.mockito.Mockito.verify;9@RunWith(MockitoJUnitRunner.class)10public class AtMostOnceTest {11 private TestInterface testInterface;12 public void testAtMostOnce() {13 testInterface.testMethod();14 testInterface.testMethod();15 testInterface.testMethod();16 testInterface.testMethod();17 testInterface.testMethod();18 verify( testInterface, atMostOnce() ).testMethod();19 verify( testInterface, times( 5 ) ).testMethod();20 }21}22package com.ack.j2se.mock;23import org.junit.Test;24import org.junit.runner.RunWith;25import org.mockito.Mock;26import org.mockito.runners.MockitoJUnitRunner;27import static org.mockito.Mockito.atMost;28import static org.mockito.Mockito.times;29import static org.mockito.Mockito.verify;30@RunWith(MockitoJUnitRunner.class)31public class AtMostTest {32 private TestInterface testInterface;33 public void testAtMost() {34 testInterface.testMethod();35 testInterface.testMethod();36 testInterface.testMethod();37 testInterface.testMethod();38 testInterface.testMethod();39 verify( testInterface, atMost( 5 ) ).testMethod();40 verify( testInterface, times( 5 ) ).testMethod();41 }42}43package com.ack.j2se.mock;44import org.junit.Test;45import org.junit.runner.RunWith;46import org.mockito.Mock;47import org.mockito.runners.MockitoJUnitRunner;48import static org.mockito.Mockito.atLeastOnce;49import static org.mockito.Mockito.times;50import static org.mockito.Mockito.verify;51@RunWith(MockitoJUnitRunner.class)52public class AtLeastOnceTest {53 private TestInterface testInterface;54 public void testAtLeastOnce() {55 testInterface.testMethod();56 testInterface.testMethod();57 testInterface.testMethod();58 testInterface.testMethod();59 testInterface.testMethod();60 verify( testInterface, atLeastOnce() ).testMethod();61 verify( testInterface, times(
atMostOnce
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.mockito.runners.MockitoJUnitRunner;7import static org.mockito.Mockito.*;8import static org.junit.Assert.*;9import java.util.*;10@RunWith(MockitoJUnitRunner.class)11public class MockitoTest {12 public void test() {13 List mockedList = mock(List.class);14 when(mockedList.get(0)).thenAnswer(new Answer<Object>() {15 private int count = 0;16 public Object answer(InvocationOnMock invocation) {17 return ++count;18 }19 });20 assertEquals(1, mockedList.get(0));21 assertEquals(2, mockedList.get(0));22 assertEquals(3, mockedList.get(0));23 }24}25import org.mockito.Mockito;26import org.mockito.invocation.InvocationOnMock;27import org.mockito.stubbing.Answer;28import org.junit.Test;29import org.junit.runner.RunWith;30import org.mockito.runners.MockitoJUnitRunner;31import static org.mockito.Mockito.*;32import static org.junit.Assert.*;33import java.util.*;34@RunWith(MockitoJUnitRunner.class)35public class MockitoTest {36 public void test() {37 List mockedList = mock(List.class);38 when(mockedList.get(0)).thenAnswer(new Answer<Object>() {39 private int count = 0;40 public Object answer(InvocationOnMock invocation) {41 return ++count;42 }43 });44 assertEquals(1, mockedList.get(0));45 assertEquals(2, mockedList.get(0));46 assertEquals(3, mockedList.get(0));47 verify(mockedList, atLeastOnce()).get(0);48 }49}50import org.mockito.Mockito;51import org.mockito.invocation.InvocationOnMock;52import org.mockito.stubbing.Answer;53import org.junit.Test;54import org.junit.runner.RunWith;55import org.mockito.runners.MockitoJUnitRunner;56import static org.mockito.Mockito.*;57import static org.junit.Assert.*;58import java.util.*;59@RunWith(MockitoJUnitRunner.class)60public class MockitoTest {61 public void test() {62 List mockedList = mock(List.class);63 when(mockedList.get
atMostOnce
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3public class 1 {4 public static void main(String[] args) {5 List mockedList = mock(List.class);6 mockedList.add("one");7 mockedList.clear();8 verify(mockedList).add("one");9 verify(mockedList).clear();10 }11}
atMostOnce
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.mockito.Mockito.*;4import org.mockito.invocation.InvocationOnMock;5import org.mockito.stubbing.Answer;6import org.mockito.verification.VerificationMode;7import org.mockito.verification.VerificationWithTimeout;8import java.util.*;9public class TestClass {10 public static void main(String[] args) {11 List<String> mockedList = mock(List.class);12 mockedList.add("one");13 mockedList.add("two");14 mockedList.add("three");15 mockedList.add("four");16 mockedList.add("five");17 mockedList.add("six");18 mockedList.add("seven");19 mockedList.add("eight");20 mockedList.add("nine");21 mockedList.add("ten");22 mockedList.add("eleven");23 mockedList.add("twelve");24 mockedList.add("thirteen");25 mockedList.add("fourteen");26 mockedList.add("fifteen");27 mockedList.add("sixteen");28 mockedList.add("seventeen");29 mockedList.add("eighteen");30 mockedList.add("nineteen");31 mockedList.add("twenty");32 mockedList.add("twenty one");33 mockedList.add("twenty two");34 mockedList.add("twenty three");35 mockedList.add("twenty four");36 mockedList.add("twenty five");37 mockedList.add("twenty six");38 mockedList.add("twenty seven");39 mockedList.add("twenty eight");40 mockedList.add("twenty nine");41 mockedList.add("thirty");42 mockedList.add("thirty one");43 mockedList.add("thirty two");44 mockedList.add("thirty three");45 mockedList.add("thirty four");46 mockedList.add("thirty five");47 mockedList.add("thirty six");48 mockedList.add("thirty seven");49 mockedList.add("thirty eight");50 mockedList.add("thirty nine");51 mockedList.add("forty");52 mockedList.add("forty one");53 mockedList.add("forty two");54 mockedList.add("forty three");55 mockedList.add("forty four");56 mockedList.add("forty five");57 mockedList.add("forty six");58 mockedList.add("forty seven");59 mockedList.add("forty eight");60 mockedList.add("forty nine");
atMostOnce
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4import static org.mockito.Mockito.*;5import java.util.List;6import java.util.LinkedList;7import java.util.Iterator;8import java.util.ListIterator;9import java.lang.reflect.Method;10import java.lang.reflect.InvocationTargetException;11import java.lang.reflect.Constructor;12import java.lang.reflect.InvocationHandler;13import java.lang.reflect.Proxy;14import java.lang.reflect.Field;15import java.lang.reflect.Modifier;16import java.util.ArrayList;17import java.util.Arrays;18import java.util.Collections;19import java.util.Comparator;20import java.util.HashMap;21import java.util.HashSet;22import java.util.Map;23import java.util.Set;24import java.util.Stack;25import java.util.regex.Matcher;26import java.util.regex.Pattern;27import java.util.concurrent.atomic.AtomicInteger;28import java.util.concurrent.atomic.AtomicReference;29import java.util.concurrent.atomic.AtomicReferenceArray;30import java.util.concurrent.atomic.AtomicLong;31import java.util.concurrent.atomic.AtomicIntegerArray;32import java.util.concurrent.atomic.AtomicLongArray;33import java.util.concurrent.atomic.AtomicBoolean;34import java.util.concurrent.locks.ReentrantLock;35import java.util.concurrent.locks.ReentrantReadWriteLock;36import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;37import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;38import java.util.concurrent.locks.Lock;39import java.util.concurrent.locks.Condition;40import java.util.concurrent.locks.ReentrantLock;41import java.util.concurrent.locks.ReentrantReadWriteLock;42import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;43import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;44import java.util.concurrent.locks.Lock;45import java.util.concurrent.locks.Condition;46import java.util.concurrent.locks.ReentrantLock;47import java.util.concurrent.locks.ReentrantReadWriteLock;48import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;49import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;50import java.util.concurrent.locks.Lock;51import java.util.concurrent.locks.Condition;52import java.util.concurrent.locks.ReentrantLock;53import java.util.concurrent.locks.ReentrantReadWriteLock;54import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;55import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;56import java.util.concurrent.locks.Lock;57import java.util.concurrent.locks.Condition;58import java.util.concurrent.locks.ReentrantLock;59import java.util.concurrent.locks.ReentrantReadWriteLock;60import java.util.concurrent.locks.ReentrantReadWriteLock.Read
atMostOnce
Using AI Code Generation
1import org.junit.Test;2import static org.mockito.Mockito.*;3public class atMostOnceTest {4 public void test(){5 MyClass test = mock(MyClass.class);6 verify(test, atMostOnce()).myMethod();7 }8}9class MyClass{10 public void myMethod(){11 }12}13BUILD SUCCESSFUL (total time: 0 seconds)
atMostOnce
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4import org.junit.Test;5import static org.mockito.Mockito.*;6import static org.junit.Assert.*;7class TestClass {8 public void foo() {9 System.out.println("foo");10 }11}12public class MyClass {13 public void test() {14 TestClass mock = mock(TestClass.class);15 doAnswer(new Answer() {16 public Object answer(InvocationOnMock invocation) throws Throwable {17 System.out.println("bar");18 return null;19 }20 }).when(mock).foo();21 mock.foo();22 mock.foo();23 }24}
atMostOnce
Using AI Code Generation
1package org.mockito;2import static org.mockito.Mockito.*;3import java.util.LinkedList;4import org.junit.Test;5public class MockitoAtMostOnce {6public void atMostOnceTest() {7LinkedList mockedList = mock(LinkedList.class);8mockedList.add("one");9mockedList.clear();10verify(mockedList).add("one");11verify(mockedList).clear();12verify(mockedList, atMostOnce()).add("one");13verify(mockedList, atMostOnce()).clear();14}15}16LinkedList.clear();17-> at org.mockito.MockitoAtMostOnce.atMostOnceTest(MockitoAtMostOnce.java:16)18at org.mockito.Mockito.verify(Mockito.java:1228)19at org.mockito.MockitoAtMostOnce.atMostOnceTest(MockitoAtMostOnce.java:19)20at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)21at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)22at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)23at java.lang.reflect.Method.invoke(Method.java:597)24at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)25at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)26at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)27at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)28at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)29at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)30at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)31at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)32at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)33at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)34at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)35at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)36at org.junit.runners.ParentRunner.run(ParentRunner.java:309)37at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
atMostOnce
Using AI Code Generation
1package com.ack.j2se.mockito;2import org.junit.Test;3import java.util.List;4import static org.mockito.Mockito.*;5public class AtMostOnceTest {6 public void testAtMostOnce() {7 List mockedList = mock( List.class );8 mockedList.add( "one" );9 mockedList.add( "two" );10 verify( mockedList, atMostOnce() ).add( "one" );11 verify( mockedList, atMostOnce() ).add( "two" );12 verify( mockedList, atMostOnce() ).add( "three" );13 }14}15package com.ack.j2se.mockito;16import org.junit.Test;17import java.util.List;18import static org.mockito.Mockito.*;19public class AtMostTest {20 public void testAtMost() {21 List mockedList = mock( List.class );22 mockedList.add( "one" );23 mockedList.add( "two" );24 mockedList.add( "three" );25 verify( mockedList, atMost( 2 ) ).add( "one" );26 verify( mockedList, atMost( 2 ) ).add( "two" );27 verify( mockedList, atMost( 2 ) ).add( "three" );28 }29}30package com.ack.j2se.mockito;31import org.junit.Test;32import java.util.List;33import static org.mockito.Mockito.*;34public class NeverTest {35 public void testNever() {36 List mockedList = mock( List.class );37 mockedList.add( "one" );38 mockedList.add( "two" );39 mockedList.add( "three" );40 verify( mockedList, never() ).add( "four" );41 }42}
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!!