Best Mockito code snippet using org.mockito.ArgumentCaptor
Source:TestMsckCreatePartitionsInBatches.java
...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}...
Source:CheckpointSpoutTest.java
...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}...
Source:ProcessorBoltTest.java
...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,...
ArgumentCaptor
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.ArgumentCaptor;4import org.mockito.Captor;5import org.mockito.Mock;6import org.mockito.runners.MockitoJUnitRunner;7import java.util.ArrayList;8import java.util.List;9import static org.junit.Assert.assertEquals;10import static org.mockito.Mockito.verify;11@RunWith(MockitoJUnitRunner.class)12public class ArgumentCaptorTest {13 List mockedList;14 ArgumentCaptor argumentCaptor;15 public void testArgumentCaptor() {16 mockedList.add("one");17 mockedList.add("two");18 mockedList.add("three");19 verify(mockedList).add(argumentCaptor.capture());20 assertEquals("three", argumentCaptor.getValue());21 }22}23OK (1 test)24 <mkdir dir="${build.dir}"/>25 <javac srcdir="${src.dir}" destdir="${build.dir}"26 classpath="${junit.jar}:${mockito-core.jar}">27 <java fork="true" dir="${build.dir}" classname="org.junit.runner.JUnitCore" classpath
ArgumentCaptor
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.ArgumentCaptor;4import org.mockito.Captor;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.runners.MockitoJUnitRunner;8import java.util.ArrayList;9import java.util.List;10import static org.junit.Assert.assertEquals;11import static org.mockito.Mockito.verify;12@RunWith(MockitoJUnitRunner.class)13public class MockitoTest {14 List mockedList;15 ArrayList mockedArrayList;16 ArgumentCaptor argCaptor;17 public void test1() {18 mockedList.add("one");19 verify(mockedList).add(argCaptor.capture());20 assertEquals("one", argCaptor.getValue());21 }22}23BUILD SUCCESSFUL (total time: 0 seconds)
ArgumentCaptor
Using AI Code Generation
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.*;7public class ArgumentCaptorTest {8 public void testArgumentCaptor() {9 List<String> mockedList = mock(ArrayList.class);10 ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);11 mockedList.add("one");12 verify(mockedList).add(argumentCaptor.capture());13 assertEquals("one", argumentCaptor.getValue());14 }15}
ArgumentCaptor
Using AI Code Generation
1import java.util.ArrayList;2import java.util.List;3import org.junit.Test;4import org.mockito.ArgumentCaptor;5import static org.junit.Assert.*;6import static org.mockito.Mockito.*;7public class Test1 {8 public void test1(){9 List<String> mockList = mock(List.class);10 mockList.add("one");11 mockList.add("two");12 mockList.add("three");13 ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);14 verify(mockList, times(3)).add(arg.capture());15 List<String> allValues = arg.getAllValues();16 assertEquals("one", allValues.get(0));17 assertEquals("two", allValues.get(1));18 assertEquals("three", allValues.get(2));19 }20}21BUILD SUCCESSFUL (total time: 0 seconds)
ArgumentCaptor
Using AI Code Generation
1package com.automationrhapsody.junit;2import java.util.List;3import org.junit.Test;4import static org.mockito.Mockito.*;5import static org.junit.Assert.assertEquals;6public class ArgumentCaptorTest {7 public void testArgumentCaptor() {8 List mockedList = mock(List.class);9 mockedList.add("one");10 mockedList.clear();11 ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);12 verify(mockedList).add(argument.capture());13 assertEquals("one", argument.getValue().get(0));14 assertEquals(0, argument.getValue().size());15 }16}17package com.automationrhapsody.junit;18import java.util.List;19import org.junit.Test;20import static org.mockito.Mockito.*;21import static org.junit.Assert.assertEquals;22public class ArgumentMatcherTest {23 public void testArgumentMatcher() {24 List mockedList = mock(List.class);25 mockedList.add("one");26 mockedList.clear();27 ArgumentMatcher<List> argument = new ArgumentMatcher<List>() {28 public boolean matches(Object argument) {29 if (argument instanceof List) {30 List list = (List) argument;31 return list.get(0).equals("one") && list.size() == 1;32 }33 return false;34 }35 };36 verify(mockedList).add(argThat(argument));37 }38}39package com.automationrhapsody.junit;40import java.util.List;41import org.junit.Test;42import static org.mockito.Mockito.*;43import static org.junit.Assert.assertEquals;44public class ArgumentCaptorTest {45 public void testArgumentCaptor() {46 List mockedList = mock(List.class);47 mockedList.add("one");48 mockedList.clear();
ArgumentCaptor
Using AI Code Generation
1import org.mockito.ArgumentCaptor;2import static org.mockito.Mockito.*;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.Mock;6import org.mockito.runners.MockitoJUnitRunner;7import java.util.List;8@RunWith(MockitoJUnitRunner.class)9public class ArgumentCaptorDemo {10 List mock;11 public void captureArgument() {12 mock.add("one");13 ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);14 verify(mock).add(argument.capture());15 System.out.println(argument.getValue());16 }17}18import org.mockito.ArgumentCaptor;19import static org.mockito.Mockito.*;20import org.junit.Test;21import org.junit.runner.RunWith;22import org.mockito.Mock;23import org.mockito.runners.MockitoJUnitRunner;24import java.util.List;25@RunWith(MockitoJUnitRunner.class)26public class ArgumentCaptorDemo {27 List mock;28 public void captureArgument() {29 mock.add("one");30 mock.add("two");31 ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);32 verify(mock, times(2)).add(argument.capture());33 System.out.println(argument.getAllValues());34 }35}36import org.mockito.ArgumentCaptor;37import static org.mockito.Mockito.*;38import org.junit.Test;39import org.junit.runner.RunWith;40import org.mockito.Mock;41import org.mockito.runners.MockitoJUnitRunner;42import java.util.List;43import static org.junit.Assert.*;44@RunWith(MockitoJUnitRunner.class)45public class ArgumentCaptorDemo {46 List mock;47 public void captureArgument() {48 mock.add("one");49 ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);50 verify(mock).add(argument.capture());51 assertEquals("one", argument.getValue());52 }53}
ArgumentCaptor
Using AI Code Generation
1import org.mockito.ArgumentCaptor;2import org.mockito.Mockito;3import static org.mockito.Mockito.*;4import java.util.*;5public class 1 {6public static void main(String[] args) {7List mockList = Mockito.mock(List.class);8ArgumentCaptor argCaptor = ArgumentCaptor.forClass(String.class);9mockList.add("Hello");10verify(mockList).add(argCaptor.capture());11System.out.println(argCaptor.getValue());12}13}
ArgumentCaptor
Using AI Code Generation
1import org.junit.Test;2import org.mockito.ArgumentCaptor;3import org.mockito.Mockito;4import static org.mockito.Mockito.*;5public class ArgumentCaptorTest {6 public void testArgumentCaptor() {7 MyList list = mock(MyList.class);8 when(list.get(0)).thenReturn("first");9 list.add("first");10 list.add("second");11 ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);12 verify(list).add(arg.capture());13 assertEquals("first", arg.getValue());14 }15}
ArgumentCaptor
Using AI Code Generation
1import org.mockito.ArgumentCaptor;2public class ArgumentCapture {3 public static void main(String[] args) {4 ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);5 argCaptor.capture();6 System.out.println(argCaptor.getValue());7 }8}9import org.mockito.ArgumentCaptor;10public class ArgumentCapture {11 public static void main(String[] args) {12 ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);13 argCaptor.capture();14 System.out.println(argCaptor.getValue());15 }16}17import org.mockito.ArgumentCaptor;18public class ArgumentCapture {19 public static void main(String[] args) {20 ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);21 argCaptor.capture();22 System.out.println(argCaptor.getValue());23 }24}25import org.mockito.ArgumentCaptor;26public class ArgumentCapture {27 public static void main(String[] args) {
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!!