How to use ArgumentCaptor method of org.mockito.ArgumentCaptor class

Best Mockito code snippet using org.mockito.ArgumentCaptor.ArgumentCaptor

Source:TestMsckCreatePartitionsInBatches.java Github

copy

Full Screen

...47import org.junit.Assert;48import org.junit.Before;49import org.junit.BeforeClass;50import org.junit.Test;51import org.mockito.ArgumentCaptor;52import org.mockito.Mockito;53public class TestMsckCreatePartitionsInBatches {54 private static HiveConf hiveConf;55 private static Msck msck;56 private final String catName = "hive";57 private final String dbName = "default";58 private final String tableName = "test_msck_batch";59 private static IMetaStoreClient db;60 private List<String> repairOutput;61 private Table table;62 @BeforeClass63 public static void setupClass() throws HiveException, MetaException {64 hiveConf = new HiveConf(TestMsckCreatePartitionsInBatches.class);65 hiveConf.setIntVar(ConfVars.HIVE_MSCK_REPAIR_BATCH_SIZE, 5);66 hiveConf.setVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER,67 "org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizerFactory");68 SessionState.start(hiveConf);69 try {70 db = new HiveMetaStoreClient(hiveConf);71 } catch (MetaException e) {72 throw new HiveException(e);73 }74 msck = new Msck( false, false);75 msck.init(hiveConf);76 }77 @Before78 public void before() throws Exception {79 createPartitionedTable(catName, dbName, tableName);80 table = db.getTable(catName, dbName, tableName);81 repairOutput = new ArrayList<String>();82 }83 @After84 public void after() throws Exception {85 cleanUpTableQuietly(catName, dbName, tableName);86 }87 private Table createPartitionedTable(String catName, String dbName, String tableName) throws Exception {88 try {89 db.dropTable(catName, dbName, tableName);90 Table table = new Table();91 table.setCatName(catName);92 table.setDbName(dbName);93 table.setTableName(tableName);94 FieldSchema col1 = new FieldSchema("key", "string", "");95 FieldSchema col2 = new FieldSchema("value", "int", "");96 FieldSchema col3 = new FieldSchema("city", "string", "");97 StorageDescriptor sd = new StorageDescriptor();98 sd.setSerdeInfo(new SerDeInfo());99 sd.setInputFormat(TextInputFormat.class.getCanonicalName());100 sd.setOutputFormat(HiveIgnoreKeyTextOutputFormat.class.getCanonicalName());101 sd.setCols(Arrays.asList(col1, col2));102 table.setPartitionKeys(Arrays.asList(col3));103 table.setSd(sd);104 db.createTable(table);105 return db.getTable(catName, dbName, tableName);106 } catch (Exception exception) {107 fail("Unable to drop and create table " + StatsUtils.getFullyQualifiedTableName(dbName, tableName) + " because "108 + StringUtils.stringifyException(exception));109 throw exception;110 }111 }112 private void cleanUpTableQuietly(String catName, String dbName, String tableName) {113 try {114 db.dropTable(catName, dbName, tableName);115 } catch (Exception exception) {116 fail("Unexpected exception: " + StringUtils.stringifyException(exception));117 }118 }119 private Set<PartitionResult> createPartsNotInMs(int numOfParts) {120 Set<PartitionResult> partsNotInMs = new HashSet<>();121 for (int i = 0; i < numOfParts; i++) {122 PartitionResult result = new PartitionResult();123 result.setPartitionName("city=dummyCity_" + String.valueOf(i));124 partsNotInMs.add(result);125 }126 return partsNotInMs;127 }128 /**129 * Tests the number of times Hive.createPartitions calls are executed with total number of130 * partitions to be added are equally divisible by batch size131 *132 * @throws Exception133 */134 @Test135 public void testNumberOfCreatePartitionCalls() throws Exception {136 // create 10 dummy partitions137 Set<PartitionResult> partsNotInMs = createPartsNotInMs(10);138 IMetaStoreClient spyDb = Mockito.spy(db);139 // batch size of 5 and decaying factor of 2140 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 5, 2, 0);141 // there should be 2 calls to create partitions with each batch size of 5142 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);143 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);144 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);145 Mockito.verify(spyDb, Mockito.times(2)).add_partitions(argParts.capture(), ifNotExistsArg.capture(), needResultsArg.capture());146 // confirm the batch sizes were 5, 5 in the two calls to create partitions147 List<List<Partition>> apds = argParts.getAllValues();148 int retryAttempt = 1;149 Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),150 5, apds.get(0).size());151 Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),152 5, apds.get(1).size());153 assertTrue(ifNotExistsArg.getValue());154 assertFalse(needResultsArg.getValue());155 }156 /**157 * Tests the number of times Hive.createPartitions calls are executed with total number of158 * partitions to be added are not exactly divisible by batch size159 *160 * @throws Exception161 */162 @Test163 public void testUnevenNumberOfCreatePartitionCalls() throws Exception {164 // create 9 dummy partitions165 Set<PartitionResult> partsNotInMs = createPartsNotInMs(9);166 IMetaStoreClient spyDb = Mockito.spy(db);167 // batch size of 5 and decaying factor of 2168 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 5, 2, 0);169 // there should be 2 calls to create partitions with batch sizes of 5, 4170 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);171 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);172 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);173 Mockito.verify(spyDb, Mockito.times(2)).add_partitions(argParts.capture(), ifNotExistsArg.capture(), needResultsArg.capture());174 // confirm the batch sizes were 5, 4 in the two calls to create partitions175 List<List<Partition>> apds = argParts.getAllValues();176 int retryAttempt = 1;177 Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),178 5, apds.get(0).size());179 Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),180 4, apds.get(1).size());181 assertTrue(ifNotExistsArg.getValue());182 assertFalse(needResultsArg.getValue());183 }184 /**185 * Tests the number of times Hive.createPartitions calls are executed with total number of186 * partitions exactly equal to batch size187 *188 * @throws Exception189 */190 @Test191 public void testEqualNumberOfPartitions() throws Exception {192 // create 13 dummy partitions193 Set<PartitionResult> partsNotInMs = createPartsNotInMs(13);194 IMetaStoreClient spyDb = Mockito.spy(db);195 // batch size of 13 and decaying factor of 2196 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 13, 2, 0);197 // there should be 1 call to create partitions with batch sizes of 13198 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);199 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);200 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);201 // there should be 1 call to create partitions with batch sizes of 13202 Mockito.verify(spyDb, Mockito.times(1)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),203 needResultsArg.capture());204 Assert.assertEquals("Unexpected number of batch size", 13,205 argParts.getValue().size());206 assertTrue(ifNotExistsArg.getValue());207 assertFalse(needResultsArg.getValue());208 }209 /**210 * Tests the number of times Hive.createPartitions calls are executed with total number of211 * partitions to is less than batch size212 *213 * @throws Exception214 */215 @Test216 public void testSmallNumberOfPartitions() throws Exception {217 // create 10 dummy partitions218 Set<PartitionResult> partsNotInMs = createPartsNotInMs(10);219 IMetaStoreClient spyDb = Mockito.spy(db);220 // batch size of 20 and decaying factor of 2221 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 20, 2, 0);222 // there should be 1 call to create partitions with batch sizes of 10223 Mockito.verify(spyDb, Mockito.times(1)).add_partitions(Mockito.anyObject(), Mockito.anyBoolean(),224 Mockito.anyBoolean());225 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);226 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);227 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);228 // there should be 1 call to create partitions with batch sizes of 10229 Mockito.verify(spyDb, Mockito.times(1)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),230 needResultsArg.capture());231 Assert.assertEquals("Unexpected number of batch size", 10,232 argParts.getValue().size());233 assertTrue(ifNotExistsArg.getValue());234 assertFalse(needResultsArg.getValue());235 }236 /**237 * Tests the number of calls to createPartitions and the respective batch sizes when first call to238 * createPartitions throws HiveException. The batch size should be reduced by the decayingFactor239 *240 * @throws Exception241 */242 @Test243 public void testBatchingWhenException() throws Exception {244 // create 13 dummy partitions245 Set<PartitionResult> partsNotInMs = createPartsNotInMs(23);246 IMetaStoreClient spyDb = Mockito.spy(db);247 // first call to createPartitions should throw exception248 Mockito.doThrow(HiveException.class).doCallRealMethod().doCallRealMethod().when(spyDb)249 .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(),250 Mockito.anyBoolean());251 // test with a batch size of 30 and decaying factor of 2252 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 0);253 // confirm the batch sizes were 23, 15, 8 in the three calls to create partitions254 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);255 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);256 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);257 // there should be 3 calls to create partitions with batch sizes of 23, 15, 8258 Mockito.verify(spyDb, Mockito.times(3)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),259 needResultsArg.capture());260 List<List<Partition>> apds = argParts.getAllValues();261 int retryAttempt = 1;262 Assert.assertEquals(263 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 23,264 apds.get(0).size());265 Assert.assertEquals(266 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 15,267 apds.get(1).size());268 Assert.assertEquals(269 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 8,270 apds.get(2).size());271 assertTrue(ifNotExistsArg.getValue());272 assertFalse(needResultsArg.getValue());273 }274 /**275 * Tests the retries exhausted case when Hive.createPartitions method call always keep throwing276 * HiveException. The batch sizes should exponentially decreased based on the decaying factor and277 * ultimately give up when it reaches 0278 *279 * @throws Exception280 */281 @Test282 public void testRetriesExhaustedBatchSize() throws Exception {283 Set<PartitionResult> partsNotInMs = createPartsNotInMs(17);284 IMetaStoreClient spyDb = Mockito.spy(db);285 Mockito.doThrow(HiveException.class).when(spyDb)286 .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(), Mockito.anyBoolean());287 // batch size of 5 and decaying factor of 2288 Exception ex = null;289 try {290 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 0);291 } catch (Exception retryEx) {292 ex = retryEx;293 }294 assertFalse("Exception was expected but was not thrown", ex == null);295 Assert.assertTrue("Unexpected class of exception thrown", ex instanceof RetryUtilities.RetryException);296 // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1297 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);298 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);299 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);300 // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1301 Mockito.verify(spyDb, Mockito.times(5)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),302 needResultsArg.capture());303 List<List<Partition>> apds = argParts.getAllValues();304 int retryAttempt = 1;305 Assert.assertEquals(306 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 17,307 apds.get(0).size());308 Assert.assertEquals(309 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 15,310 apds.get(1).size());311 Assert.assertEquals(312 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 7,313 apds.get(2).size());314 Assert.assertEquals(315 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 3,316 apds.get(3).size());317 Assert.assertEquals(318 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 1,319 apds.get(4).size());320 assertTrue(ifNotExistsArg.getValue());321 assertFalse(needResultsArg.getValue());322 }323 /**324 * Tests the maximum retry attempts provided by configuration325 * @throws Exception326 */327 @Test328 public void testMaxRetriesReached() throws Exception {329 Set<PartitionResult> partsNotInMs = createPartsNotInMs(17);330 IMetaStoreClient spyDb = Mockito.spy(db);331 Mockito.doThrow(HiveException.class).when(spyDb)332 .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(), Mockito.anyBoolean());333 // batch size of 5 and decaying factor of 2334 Exception ex = null;335 try {336 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 2);337 } catch (Exception retryEx) {338 ex = retryEx;339 }340 assertFalse("Exception was expected but was not thrown", ex == null);341 Assert.assertTrue("Unexpected class of exception thrown", ex instanceof RetryUtilities.RetryException);342 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);343 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);344 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);345 Mockito.verify(spyDb, Mockito.times(2)).add_partitions(argParts.capture(), ifNotExistsArg.capture(), needResultsArg.capture());346 List<List<Partition>> apds = argParts.getAllValues();347 int retryAttempt = 1;348 Assert.assertEquals(349 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 17,350 apds.get(0).size());351 Assert.assertEquals(352 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 15,353 apds.get(1).size());354 assertTrue(ifNotExistsArg.getValue());355 assertFalse(needResultsArg.getValue());356 }357 /**358 * Tests when max number of retries is set to 1. In this case the number of retries should359 * be specified360 * @throws Exception361 */362 @Test363 public void testOneMaxRetries() throws Exception {364 Set<PartitionResult> partsNotInMs = createPartsNotInMs(17);365 IMetaStoreClient spyDb = Mockito.spy(db);366 Mockito.doThrow(HiveException.class).when(spyDb)367 .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(), Mockito.anyBoolean());368 // batch size of 5 and decaying factor of 2369 Exception ex = null;370 try {371 msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 1);372 } catch (Exception retryEx) {373 ex = retryEx;374 }375 assertFalse("Exception was expected but was not thrown", ex == null);376 Assert.assertTrue("Unexpected class of exception thrown", ex instanceof RetryUtilities.RetryException);377 // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1378 ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);379 ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);380 ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);381 // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1382 Mockito.verify(spyDb, Mockito.times(1)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),383 needResultsArg.capture());384 List<List<Partition>> apds = argParts.getAllValues();385 int retryAttempt = 1;386 Assert.assertEquals(387 String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 17,388 apds.get(0).size());389 assertTrue(ifNotExistsArg.getValue());390 assertFalse(needResultsArg.getValue());391 }392}...

Full Screen

Full Screen

Source:CheckpointSpoutTest.java Github

copy

Full Screen

...23import org.apache.storm.tuple.Values;24import org.apache.storm.utils.Utils;25import org.junit.Before;26import org.junit.Test;27import org.mockito.ArgumentCaptor;28import org.mockito.Mockito;29import java.util.HashMap;30import java.util.Map;31import static org.apache.storm.spout.CheckPointState.State.COMMITTED;32import static org.junit.Assert.assertEquals;33import static org.apache.storm.spout.CheckPointState.Action;34/**35 * Unit test for {@link CheckpointSpout}36 */37public class CheckpointSpoutTest {38 CheckpointSpout spout = new CheckpointSpout();39 TopologyContext mockTopologyContext;40 SpoutOutputCollector mockOutputCollector;41 @Before42 public void setUp() throws Exception {43 mockTopologyContext = Mockito.mock(TopologyContext.class);44 Mockito.when(mockTopologyContext.getThisComponentId()).thenReturn("test");45 Mockito.when(mockTopologyContext.getThisTaskId()).thenReturn(1);46 mockOutputCollector = Mockito.mock(SpoutOutputCollector.class);47 }48 @Test49 public void testInitState() throws Exception {50 spout.open(new HashMap(), mockTopologyContext, mockOutputCollector);51 spout.nextTuple();52 Values expectedTuple = new Values(-1L, Action.INITSTATE);53 ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);54 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);55 ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);56 Mockito.verify(mockOutputCollector).emit(stream.capture(),57 values.capture(),58 msgId.capture());59 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());60 assertEquals(expectedTuple, values.getValue());61 assertEquals(-1L, msgId.getValue());62 spout.ack(-1L);63 Mockito.verify(mockOutputCollector).emit(stream.capture(),64 values.capture(),65 msgId.capture());66 expectedTuple = new Values(-1L, Action.INITSTATE);67 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());68 assertEquals(expectedTuple, values.getValue());69 assertEquals(-1L, msgId.getValue());70 }71 @Test72 public void testPrepare() throws Exception {73 spout.open(new HashMap(), mockTopologyContext, mockOutputCollector);74 ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);75 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);76 ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);77 spout.nextTuple();78 spout.ack(-1L);79 spout.nextTuple();80 Mockito.verify(mockOutputCollector, Mockito.times(2)).emit(stream.capture(),81 values.capture(),82 msgId.capture());83 Values expectedTuple = new Values(0L, Action.PREPARE);84 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());85 assertEquals(expectedTuple, values.getValue());86 assertEquals(0L, msgId.getValue());87 }88 @Test89 public void testPrepareWithFail() throws Exception {90 Map<String, Object> stormConf = new HashMap<>();91 KeyValueState<String, CheckPointState> state =92 (KeyValueState<String, CheckPointState>) StateFactory.getState("__state", stormConf, mockTopologyContext);93 CheckPointState txState = new CheckPointState(-1, COMMITTED);94 state.put("__state", txState);95 spout.open(mockTopologyContext, mockOutputCollector, 0, state);96 ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);97 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);98 ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);99 spout.nextTuple();100 spout.ack(-1L);101 Utils.sleep(10);102 spout.nextTuple();103 spout.ack(0L);104 Utils.sleep(10);105 spout.nextTuple();106 spout.ack(0L);107 Utils.sleep(10);108 spout.nextTuple();109 spout.fail(1L);110 Utils.sleep(10);111 spout.nextTuple();112 spout.fail(1L);113 Utils.sleep(10);114 spout.nextTuple();115 spout.ack(1L);116 Utils.sleep(10);117 spout.nextTuple();118 spout.ack(0L);119 Utils.sleep(10);120 spout.nextTuple();121 Mockito.verify(mockOutputCollector, Mockito.times(8)).emit(stream.capture(),122 values.capture(),123 msgId.capture());124 Values expectedTuple = new Values(1L, Action.PREPARE);125 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());126 assertEquals(expectedTuple, values.getValue());127 assertEquals(1L, msgId.getValue());128 }129 @Test130 public void testCommit() throws Exception {131 Map<String, Object> stormConf = new HashMap();132 stormConf.put(Config.TOPOLOGY_STATE_CHECKPOINT_INTERVAL, 0);133 spout.open(stormConf, mockTopologyContext, mockOutputCollector);134 ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);135 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);136 ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);137 spout.nextTuple();138 spout.ack(-1L);139 spout.nextTuple();140 spout.ack(0L);141 Utils.sleep(10);142 spout.nextTuple();143 spout.fail(0L);144 Utils.sleep(10);145 spout.nextTuple();146 Mockito.verify(mockOutputCollector, Mockito.times(4)).emit(stream.capture(),147 values.capture(),148 msgId.capture());149 Values expectedTuple = new Values(0L, Action.COMMIT);150 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());151 assertEquals(expectedTuple, values.getValue());152 assertEquals(0L, msgId.getValue());153 }154 @Test155 public void testRecoveryRollback() throws Exception {156 Map<String, Object> stormConf = new HashMap();157 KeyValueState<String, CheckPointState> state =158 (KeyValueState<String, CheckPointState>) StateFactory.getState("test-1", stormConf, mockTopologyContext);159 CheckPointState checkPointState = new CheckPointState(100, CheckPointState.State.PREPARING);160 state.put("__state", checkPointState);161 spout.open(mockTopologyContext, mockOutputCollector, 0, state);162 ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);163 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);164 ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);165 spout.nextTuple();166 Mockito.verify(mockOutputCollector, Mockito.times(1)).emit(stream.capture(),167 values.capture(),168 msgId.capture());169 Values expectedTuple = new Values(100L, Action.ROLLBACK);170 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());171 assertEquals(expectedTuple, values.getValue());172 assertEquals(100L, msgId.getValue());173 }174 @Test175 public void testRecoveryRollbackAck() throws Exception {176 Map<String, Object> stormConf = new HashMap();177 KeyValueState<String, CheckPointState> state =178 (KeyValueState<String, CheckPointState>) StateFactory.getState("test-1", stormConf, mockTopologyContext);179 CheckPointState checkPointState = new CheckPointState(100, CheckPointState.State.PREPARING);180 state.put("__state", checkPointState);181 spout.open(mockTopologyContext, mockOutputCollector, 0, state);182 ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);183 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);184 ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);185 spout.nextTuple();186 spout.ack(100L);187 spout.nextTuple();188 spout.ack(99L);189 spout.nextTuple();190 Mockito.verify(mockOutputCollector, Mockito.times(3)).emit(stream.capture(),191 values.capture(),192 msgId.capture());193 Values expectedTuple = new Values(100L, Action.PREPARE);194 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());195 assertEquals(expectedTuple, values.getValue());196 assertEquals(100L, msgId.getValue());197 }198 @Test199 public void testRecoveryCommit() throws Exception {200 Map<String, Object> stormConf = new HashMap();201 KeyValueState<String, CheckPointState> state =202 (KeyValueState<String, CheckPointState>) StateFactory.getState("test-1", stormConf, mockTopologyContext);203 CheckPointState checkPointState = new CheckPointState(100, CheckPointState.State.COMMITTING);204 state.put("__state", checkPointState);205 spout.open(mockTopologyContext, mockOutputCollector, 0, state);206 ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);207 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);208 ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);209 spout.nextTuple();210 Mockito.verify(mockOutputCollector, Mockito.times(1)).emit(stream.capture(),211 values.capture(),212 msgId.capture());213 Values expectedTuple = new Values(100L, Action.COMMIT);214 assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());215 assertEquals(expectedTuple, values.getValue());216 assertEquals(100L, msgId.getValue());217 }218}...

Full Screen

Full Screen

Source:ProcessorBoltTest.java Github

copy

Full Screen

...30import org.jgrapht.DirectedGraph;31import org.jgrapht.graph.DefaultDirectedGraph;32import org.junit.Before;33import org.junit.Test;34import org.mockito.ArgumentCaptor;35import org.mockito.Mockito;36import java.util.Collection;37import java.util.Collections;38import java.util.HashMap;39import java.util.Map;40import java.util.Set;41import static org.junit.Assert.assertArrayEquals;42import static org.junit.Assert.assertEquals;43/**44 * Unit tests for {@link ProcessorBolt}45 */46public class ProcessorBoltTest {47 TopologyContext mockTopologyContext;48 OutputCollector mockOutputCollector;49 ProcessorBolt bolt;50 Tuple mockTuple1;51 Tuple mockTuple2;52 Tuple mockTuple3;53 Tuple punctuation;54 Multimap<String, ProcessorNode> mockStreamToProcessors;55 DirectedGraph<Node, Edge> graph;56 @Before57 public void setUp() throws Exception {58 mockTopologyContext = Mockito.mock(TopologyContext.class);59 mockOutputCollector = Mockito.mock(OutputCollector.class);60 mockTuple1 = Mockito.mock(Tuple.class);61 mockTuple2 = Mockito.mock(Tuple.class);62 mockTuple3 = Mockito.mock(Tuple.class);63 setUpMockTuples(mockTuple1, mockTuple2, mockTuple3);64 punctuation = Mockito.mock(Tuple.class);65 setUpPunctuation(punctuation);66 mockStreamToProcessors = Mockito.mock(Multimap.class);67 graph = new DefaultDirectedGraph(new StreamsEdgeFactory());68 }69 @Test70 public void testEmitAndAck() throws Exception {71 setUpProcessorBolt(new FilterProcessor<Integer>(x -> true));72 bolt.execute(mockTuple1);73 ArgumentCaptor<Collection> anchor = ArgumentCaptor.forClass(Collection.class);74 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);75 ArgumentCaptor<String> os = ArgumentCaptor.forClass(String.class);76 Mockito.verify(mockOutputCollector).emit(os.capture(), anchor.capture(), values.capture());77 assertEquals("outputstream", os.getValue());78 assertArrayEquals(new Object[]{mockTuple1}, anchor.getValue().toArray());79 assertEquals(new Values(100), values.getValue());80 Mockito.verify(mockOutputCollector, Mockito.times(1)).ack(mockTuple1);81 }82 @Test83 public void testAggResultAndAck() throws Exception {84 setUpProcessorBolt(new AggregateProcessor<>(new LongSum()), Collections.singleton("inputstream"), true, null);85 bolt.execute(mockTuple2);86 bolt.execute(mockTuple3);87 bolt.execute(punctuation);88 ArgumentCaptor<Collection> anchor = ArgumentCaptor.forClass(Collection.class);89 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);90 ArgumentCaptor<String> os = ArgumentCaptor.forClass(String.class);91 Mockito.verify(mockOutputCollector, Mockito.times(2)).emit(os.capture(), anchor.capture(), values.capture());92 assertArrayEquals(new Object[]{mockTuple2, mockTuple3, punctuation}, anchor.getAllValues().get(0).toArray());93 assertArrayEquals(new Object[]{mockTuple2, mockTuple3, punctuation}, anchor.getAllValues().get(1).toArray());94 assertArrayEquals(new Object[]{new Values(200L), new Values("__punctuation")}, values.getAllValues().toArray());95 assertArrayEquals(new Object[]{"outputstream", "outputstream__punctuation"}, os.getAllValues().toArray());96 Mockito.verify(mockOutputCollector).ack(mockTuple2);97 Mockito.verify(mockOutputCollector).ack(mockTuple3);98 Mockito.verify(mockOutputCollector).ack(punctuation);99 }100 @Test101 public void testEmitTs() throws Exception {102 Tuple tupleWithTs = Mockito.mock(Tuple.class);103 setUpMockTuples(tupleWithTs);104 Mockito.when(tupleWithTs.getLongByField("ts")).thenReturn(12345L);105 setUpProcessorBolt(new FilterProcessor(x -> true), "ts");106 bolt.execute(tupleWithTs);107 ArgumentCaptor<Collection> anchor = ArgumentCaptor.forClass(Collection.class);108 ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);109 ArgumentCaptor<String> os = ArgumentCaptor.forClass(String.class);110 Mockito.verify(mockOutputCollector).emit(os.capture(), anchor.capture(), values.capture());111 assertEquals("outputstream", os.getValue());112 assertArrayEquals(new Object[]{tupleWithTs}, anchor.getValue().toArray());113 assertEquals(new Values(100, 12345L), values.getValue());114 Mockito.verify(mockOutputCollector, Mockito.times(1)).ack(tupleWithTs);115 }116 private void setUpProcessorBolt(Processor<?> processor) {117 setUpProcessorBolt(processor, Collections.emptySet(), false, null);118 }119 private void setUpProcessorBolt(Processor<?> processor, String tsFieldName) {120 setUpProcessorBolt(processor, Collections.emptySet(), false, tsFieldName);121 }122 private void setUpProcessorBolt(Processor<?> processor,123 Set<String> windowedParentStreams,...

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import org.mockito.ArgumentCaptor;3import java.util.ArrayList;4import java.util.List;5import static org.junit.Assert.assertEquals;6import static org.mockito.Mockito.mock;7import static org.mockito.Mockito.verify;8public class ArgumentCaptorTest {9 public void testArgumentCaptor() {10 List<String> mockList = mock(ArrayList.class);11 mockList.add("one");12 mockList.add("two");13 ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);14 verify(mockList).add(argument.capture());15 assertEquals("two", argument.getValue());16 }17}

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentCaptor;2import org.mockito.Mockito;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5import org.mockito.stubbing.OngoingStubbing;6import org.mockito.verification.VerificationMode;7import org.mockito.verification.VerificationWithTimeout;8import org.mockito.verification.VerificationWithTimeoutBuilder;9import org.mockito.verification.VerificationWithTimeoutMode;10import java.util.List;11import java.util.concurrent.TimeUnit;12public class MockitoArgumentCaptor {13 public static void main(String[] args) {14 List mockedList = Mockito.mock(List.class);15 mockedList.add("one");16 mockedList.clear();17 Mockito.verify(mockedList).add("one");18 Mockito.verify(mockedList).clear();19 ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);20 Mockito.verify(mockedList).add(argument.capture());21 System.out.println(argument.getValue());22 Mockito.when(mockedList.get(0)).thenReturn("first");23 System.out.println(mockedList.get(0));24 System.out.println(mockedList.get(999));

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1package com.automationrhapsody.mockito;2import static org.junit.Assert.assertEquals;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.verify;5import java.util.List;6import org.junit.Test;7import org.mockito.ArgumentCaptor;8public class ArgumentCaptorTest {9 public void testArgumentCaptor() {10 List mockedList = mock(List.class);11 mockedList.add("one");12 mockedList.clear();13 ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);14 verify(mockedList).addAll(argument.capture());15 assertEquals(1, argument.getValue().size());16 }17}18-> at com.automationrhapsody.mockito.ArgumentCaptorTest.testArgumentCaptor(ArgumentCaptorTest.java:21)19 someMethod(anyObject(), "raw String");20 someMethod(anyObject(), eq("String by matcher"));21at com.automationrhapsody.mockito.ArgumentCaptorTest.testArgumentCaptor(ArgumentCaptorTest.java:21)

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1package com.automationintesting.unit;2import com.automationintesting.model.db.Booking;3import com.automationintesting.model.db.Room;4import com.automationintesting.model.db.Rooms;5import com.automationintesting.model.db.Schedule;6import com.automationintesting.service.BookingService;7import org.junit.Before;8import org.junit.Test;9import org.junit.runner.RunWith;10import org.mockito.ArgumentCaptor;11import org.mockito.Captor;12import org.mockito.Mock;13import org.mockito.runners.MockitoJUnitRunner;14import java.util.ArrayList;15import java.util.Arrays;16import java.util.List;17import static org.junit.Assert.*;18import static org.mockito.Mockito.*;19@RunWith(MockitoJUnitRunner.class)20public class BookingServiceTest {21 private Rooms rooms;22 private Schedule schedule;23 private ArgumentCaptor<Booking> bookingCaptor;24 private BookingService bookingService;25 public void setup(){26 bookingService = new BookingService(rooms, schedule);27 }28 public void testGetBookings() {29 when(schedule.getBookings()).thenReturn(new ArrayList<Booking>());30 List<Booking> bookings = bookingService.getBookings();31 assertEquals(0, bookings.size());32 }33 public void testGetBookingsByRoomId() {34 when(schedule.getBookingsByRoomId(100)).thenReturn(new ArrayList<Booking>());35 List<Booking> bookings = bookingService.getBookingsByRoomId(100);36 assertEquals(0, bookings.size());37 }38 public void testGetBookingsByRoomIdNotFound() {39 when(schedule.getBookingsByRoomId(100)).thenReturn(null);40 List<Booking> bookings = bookingService.getBookingsByRoomId(100);41 assertNull(bookings);42 }43 public void testGetBookingsByRoomIdAndDate() {44 when(schedule.getBookingsByRoomIdAndDate(100, "2017-01-01")).thenReturn(new ArrayList<Booking>());45 List<Booking> bookings = bookingService.getBookingsByRoomIdAndDate(100, "2017-01-01");46 assertEquals(0, bookings.size());47 }48 public void testGetBookingsByRoomIdAndDateNotFound() {49 when(schedule.getBookingsByRoomIdAndDate(100, "2017-01

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentCaptor;2import org.mockito.Mock;3import org.mockito.MockitoAnnotations;4import org.mockito.Spy;5import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;6import org.mockito.exceptions.misusing.MissingMethodInvocationException;7import org.mockito.exceptions.misusing.UnfinishedVerificationException;8import org.mockito.exceptions.misusing.UnfinishedStubbingException;9import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;10import org.mockito.exceptions.verification.NoInteractionsWanted;11import org.mockito.exceptions.verification.TooLittleActualInvocations;12import org.mockito.exceptions.verification.TooManyActualInvocations;13import org.mockito.exceptions.verification.VerificationInOrderFailure;14import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;15import org.mockito.exceptions.verification.junit.JUnitNoInteractionsWanted;16import org.mockito.exceptions.verification.junit.JUnitNoMoreInteractionsAllowed;17import org.mockito.exceptions.verification.junit.JUnitTooLittleActualInvocations;18import org.mockito.exceptions.verification.junit.JUnitTooManyActualInvocations;19import org.mockito.internal.configuration.plugins.Plugins;20import org.mockito.internal.invocation.InvocationMatcher;21import org.mockito.internal.invocation.InvocationMatcherBuilder;22import org.mockito.internal.invocation.InvocationsFinder;23import org.mockito.internal.invocation.MatchersBinder;24import org.mockito.internal.invocation.MockitoMethod;25import org.mockito.internal.invocation.MockitoMethodProxy;26import org.mockito.internal.invocation.realmethod.CGLIBMockMaker;27import org.mockito.internal.invocation.realmethod.DefaultRealMethod;28import org.mockito.internal.invocation.realmethod.RealMethod;29import org.mockito.internal.invocation.realmethod.RealMethod2;30import org.mockito.internal.invocation.realmethod.RealMethodDispatcher;31import org.mockito.internal.progress.ThreadSafeMockingProgress;32import org.mockito.internal.stubbing.answers.CallsRealMethods;33import org.mockito.internal.stubbing.answers.Returns;34import org.mockito.internal.stubbing.answers.ThrowsException;35import org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations;36import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;37import org.mockito.internal.stubbing.defaultanswers.ReturnsMocks;38import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls;39import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNullsTest;40import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues;41import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValuesTest;42import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValuesTest.ReturnsMoreEmptyValuesTest2

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentCaptor;2import org.mockito.Mockito;3import org.mockito.internal.util.reflection.Whitebox;4import org.mockito.invocation.InvocationOnMock;5import org.mockito.stubbing.Answer;6import java.util.List;7public class MockitoArgumentCaptor {8 public static void main(String[] args) {9 List mockedList = Mockito.mock(List.class);10 ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);11 Mockito.when(mockedList.get(Mockito.anyInt())).thenAnswer(new Answer() {12 public Object answer(InvocationOnMock invocation) {13 Object[] args = invocation.getArguments();14 Object mock = invocation.getMock();15 return "called with arguments: " + args;16 }17 });18 mockedList.get(0);19 mockedList.get(1);20 Mockito.verify(mockedList).get(argument.capture());21 System.out.println("Argument Captured is: " + argument.getValue());22 }23}24import org.junit.Before;25import org.junit.Test;26import org.mockito.ArgumentCaptor;27import org.mockito.Mock;28import org.mockito.MockitoAnnotations;29import org.mockito.invocation.InvocationOnMock;30import org.mockito.stubbing.Answer;31import java.util.ArrayList;32import java.util.List;33import static org.junit.Assert.assertEquals;34import static org.mockito.Mockito.*;35public class MockitoArgumentCaptorTest {36 private List<String> list;37 private ArgumentCaptor<String> argumentCaptor;38 public void setUp() {39 MockitoAnnotations.initMocks(this);40 argumentCaptor = ArgumentCaptor.forClass(String.class);41 }42 public void shouldCaptureArgument() {43 list.add("one");44 verify(list).add(argumentCaptor.capture());45 assertEquals("one", argumentCaptor.getValue());46 }47 public void shouldCaptureMultipleArgumentValues() {48 list.add("one");49 list.add("two");50 verify(list, times(2)).add(argumentCaptor.capture());51 List<String> capturedArguments = argumentCaptor.getAllValues();52 assertEquals("one", capturedArguments.get(0));53 assertEquals("two", capturedArguments.get(1));54 }55 public void shouldCaptureArgumentForStubbing() {56 when(list.get(anyInt())).thenAnswer(new Answer<String>() {57 public String answer(InvocationOnMock invocation)

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentCaptor;2import org.mockito.Mockito;3public class MockitoArgumentCaptor {4 public static void main(String[] args) {5 List mockedList = Mockito.mock(List.class);6 mockedList.add("one");7 mockedList.clear();8 Mockito.verify(mockedList).add("one");9 Mockito.verify(mockedList).clear();10 ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);11 Mockito.verify(mockedList).add(argument.capture());12 System.out.println(argument.getValue());13 }14}

Full Screen

Full Screen

ArgumentCaptor

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentCaptor;2import org.mockito.Mockito;3import static org.mockito.Mockito.*;4import java.util.List;5import java.util.ArrayList;6public class 1 {7 public static void main(String[] args) {8 List mockList = Mockito.mock(List.class);9 ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);10 mockList.add("one");11 mockList.add("two");12 verify(mockList).add(argument.capture());13 System.out.println("Argument Captured: "+argument.getValue());14 }15}16import org.mockito.ArgumentCaptor;17import org.mockito.Mockito;18import static org.mockito.Mockito.*;19import java.util.List;20import java.util.ArrayList;21public class 2 {22 public static void main(String[] args) {23 List mockList = Mockito.mock(List.class);24 ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);25 mockList.add("one");26 mockList.add("two");27 verify(mockList).add(argument.capture());28 System.out.println("Argument Captured: "+argument.getValue());29 }30}31import org.mockito.ArgumentCaptor;32import org.mockito.Mockito;33import static org.mockito.Mockito.*;34import java.util.List;35import java.util.ArrayList;36public class 3 {37 public static void main(String[] args) {38 List mockList = Mockito.mock(List.class);39 ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);40 mockList.add("one");41 mockList.add("two");42 verify(mockList).add(argument.capture());43 System.out.println("Argument Captured:

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in ArgumentCaptor

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful