Best Mockito code snippet using org.mockito.ArgumentMatchers.anyListOf
Source:DropwizardExportsTest.java
...19import static org.junit.Assert.assertNotNull;20import static org.junit.Assert.assertThat;21import static org.junit.Assert.assertTrue;22import static org.mockito.ArgumentMatchers.anyDouble;23import static org.mockito.ArgumentMatchers.anyListOf;24import static org.mockito.ArgumentMatchers.anyString;25import static org.mockito.ArgumentMatchers.eq;26public class DropwizardExportsTest {27 private CollectorRegistry registry = new CollectorRegistry();28 private MetricRegistry metricRegistry;29 private SampleBuilder sampleBuilder;30 @Before31 public void setUp() {32 metricRegistry = new MetricRegistry();33 sampleBuilder = Mockito.mock(SampleBuilder.class);34 new DropwizardExports(metricRegistry, sampleBuilder).register(registry);35 }36 @Test37 public void testCounter() {38 Mockito.when(sampleBuilder.createSample("foo.bar", "", Collections.<String>emptyList(), Collections.<String>emptyList(), 1d)).thenReturn(new Collector.MetricFamilySamples.Sample("foo_bar", Collections.<String>emptyList(), Collections.<String>emptyList(), 1d));39 metricRegistry.counter("foo.bar").inc();40 assertEquals(new Double(1),41 registry.getSampleValue("foo_bar")42 );43 }44 @Test45 public void testGauge() {46 Gauge<Integer> integerGauge = new Gauge<Integer>() {47 @Override48 public Integer getValue() {49 return 1234;50 }51 };52 Gauge<Double> doubleGauge = new Gauge<Double>() {53 @Override54 public Double getValue() {55 return 1.234D;56 }57 };58 Gauge<Long> longGauge = new Gauge<Long>() {59 @Override60 public Long getValue() {61 return 1234L;62 }63 };64 Gauge<Float> floatGauge = new Gauge<Float>() {65 @Override66 public Float getValue() {67 return 0.1234F;68 }69 };70 Gauge<Boolean> booleanGauge = new Gauge<Boolean>() {71 @Override72 public Boolean getValue() {73 return true;74 }75 };76 Mockito.when(sampleBuilder.createSample("integer.gauge", "", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234)).thenReturn(new Collector.MetricFamilySamples.Sample("integer_gauge", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234));77 Mockito.when(sampleBuilder.createSample("long.gauge", "", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234)).thenReturn(new Collector.MetricFamilySamples.Sample("long_gauge", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234));78 Mockito.when(sampleBuilder.createSample("double.gauge", "", Collections.<String>emptyList(), Collections.<String>emptyList(), 1.234)).thenReturn(new Collector.MetricFamilySamples.Sample("double_gauge", Collections.<String>emptyList(), Collections.<String>emptyList(), 1.234));79 Mockito.when(sampleBuilder.createSample("float.gauge", "", Collections.<String>emptyList(), Collections.<String>emptyList(), 0.1234F)).thenReturn(new Collector.MetricFamilySamples.Sample("float_gauge", Collections.<String>emptyList(), Collections.<String>emptyList(), 0.1234F));80 Mockito.when(sampleBuilder.createSample("boolean.gauge", "", Collections.<String>emptyList(), Collections.<String>emptyList(), 1)).thenReturn(new Collector.MetricFamilySamples.Sample("boolean_gauge", Collections.<String>emptyList(), Collections.<String>emptyList(), 1));81 metricRegistry.register("double.gauge", doubleGauge);82 metricRegistry.register("long.gauge", longGauge);83 metricRegistry.register("integer.gauge", integerGauge);84 metricRegistry.register("float.gauge", floatGauge);85 metricRegistry.register("boolean.gauge", booleanGauge);86 assertEquals(new Double(1234),87 registry.getSampleValue("integer_gauge", new String[]{}, new String[]{}));88 assertEquals(new Double(1234),89 registry.getSampleValue("long_gauge", new String[]{}, new String[]{}));90 assertEquals(new Double(1.234),91 registry.getSampleValue("double_gauge", new String[]{}, new String[]{}));92 assertEquals(new Double(0.1234F),93 registry.getSampleValue("float_gauge", new String[]{}, new String[]{}));94 assertEquals(new Double(1),95 registry.getSampleValue("boolean_gauge", new String[]{}, new String[]{}));96 }97 @Test98 public void testInvalidGaugeType() {99 Gauge<String> invalidGauge = new Gauge<String>() {100 @Override101 public String getValue() {102 return "foobar";103 }104 };105 metricRegistry.register("invalid_gauge", invalidGauge);106 assertEquals(null, registry.getSampleValue("invalid_gauge"));107 Mockito.verifyZeroInteractions(sampleBuilder);108 }109 @Test110 public void testGaugeReturningNullValue() {111 Gauge<String> invalidGauge = new Gauge<String>() {112 @Override113 public String getValue() {114 return null;115 }116 };117 metricRegistry.register("invalid_gauge", invalidGauge);118 assertEquals(null, registry.getSampleValue("invalid_gauge"));119 Mockito.verifyZeroInteractions(sampleBuilder);120 }121 void assertRegistryContainsMetrics(String... metrics) {122 for (String metric : metrics) {123 assertNotEquals(String.format("Metric %s should exist", metric), null,124 registry.getSampleValue(metric, new String[]{}, new String[]{}));125 }126 }127 @Test128 public void testHistogram() throws IOException {129 // just test the standard mapper130 final MetricRegistry metricRegistry = new MetricRegistry();131 final CollectorRegistry registry = new CollectorRegistry();132 new DropwizardExports(metricRegistry).register(registry);133 Histogram hist = metricRegistry.histogram("hist");134 int i = 0;135 while (i < 100) {136 hist.update(i);137 i += 1;138 }139 assertEquals(new Double(100), registry.getSampleValue("hist_count"));140 for (Double d : Arrays.asList(0.75, 0.95, 0.98, 0.99)) {141 assertEquals(new Double((d - 0.01) * 100), registry.getSampleValue("hist",142 new String[]{"quantile"}, new String[]{d.toString()}));143 }144 assertEquals(new Double(99), registry.getSampleValue("hist", new String[]{"quantile"},145 new String[]{"0.999"}));146 }147 @Test148 public void testMeter() throws IOException, InterruptedException {149 Mockito.when(sampleBuilder.createSample("meter", "_total", Collections.<String>emptyList(), Collections.<String>emptyList(), 2)).thenReturn(new Collector.MetricFamilySamples.Sample("meter_total", Collections.<String>emptyList(), Collections.<String>emptyList(), 2));150 Meter meter = metricRegistry.meter("meter");151 meter.mark();152 meter.mark();153 assertEquals(new Double(2), registry.getSampleValue("meter_total"));154 }155 @Test156 public void testTimer() throws IOException, InterruptedException {157 // just test the standard mapper158 final MetricRegistry metricRegistry = new MetricRegistry();159 final CollectorRegistry registry = new CollectorRegistry();160 new DropwizardExports(metricRegistry).register(registry);161 Timer t = metricRegistry.timer("timer");162 Timer.Context time = t.time();163 Thread.sleep(1L);164 time.stop();165 // We slept for 1Ms so we ensure that all timers are above 1ms:166 assertTrue(registry.getSampleValue("timer", new String[]{"quantile"}, new String[]{"0.99"}) > 0.001);167 assertEquals(new Double(1.0D), registry.getSampleValue("timer_count"));168 }169 @Test170 public void testThatMetricHelpUsesOriginalDropwizardName() {171 Mockito.when(sampleBuilder.createSample(eq("my.application.namedTimer1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))172 .thenReturn(new Collector.MetricFamilySamples.Sample("my_application_namedTimer1", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234));173 Mockito.when(sampleBuilder.createSample(eq("my.application.namedCounter1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))174 .thenReturn(new Collector.MetricFamilySamples.Sample("my_application_namedCounter1", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234));175 Mockito.when(sampleBuilder.createSample(eq("my.application.namedMeter1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))176 .thenReturn(new Collector.MetricFamilySamples.Sample("my_application_namedMeter1_total", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234));177 Mockito.when(sampleBuilder.createSample(eq("my.application.namedHistogram1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))178 .thenReturn(new Collector.MetricFamilySamples.Sample("my_application_namedHistogram1", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234));179 Mockito.when(sampleBuilder.createSample(eq("my.application.namedGauge1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))180 .thenReturn(new Collector.MetricFamilySamples.Sample("my_application_namedGauge1", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234));181 metricRegistry.timer("my.application.namedTimer1");182 metricRegistry.counter("my.application.namedCounter1");183 metricRegistry.meter("my.application.namedMeter1");184 metricRegistry.histogram("my.application.namedHistogram1");185 metricRegistry.register("my.application.namedGauge1", new ExampleDoubleGauge());186 Enumeration<Collector.MetricFamilySamples> metricFamilySamples = registry.metricFamilySamples();187 Map<String, Collector.MetricFamilySamples> elements = new HashMap<String, Collector.MetricFamilySamples>();188 while (metricFamilySamples.hasMoreElements()) {189 Collector.MetricFamilySamples element = metricFamilySamples.nextElement();190 elements.put(element.name, element);191 }192 assertEquals(5, elements.size());193 assertTrue(elements.keySet().contains("my_application_namedTimer1"));194 assertTrue(elements.keySet().contains("my_application_namedCounter1"));195 assertTrue(elements.keySet().contains("my_application_namedMeter1_total"));196 assertTrue(elements.keySet().contains("my_application_namedHistogram1"));197 assertTrue(elements.keySet().contains("my_application_namedGauge1"));198 assertThat(elements.get("my_application_namedTimer1").help,199 is("Generated from Dropwizard metric import (metric=my.application.namedTimer1, type=com.codahale.metrics.Timer)"));200 assertThat(elements.get("my_application_namedCounter1").help,201 is("Generated from Dropwizard metric import (metric=my.application.namedCounter1, type=com.codahale.metrics.Counter)"));202 assertThat(elements.get("my_application_namedMeter1_total").help,203 is("Generated from Dropwizard metric import (metric=my.application.namedMeter1, type=com.codahale.metrics.Meter)"));204 assertThat(elements.get("my_application_namedHistogram1").help,205 is("Generated from Dropwizard metric import (metric=my.application.namedHistogram1, type=com.codahale.metrics.Histogram)"));206 assertThat(elements.get("my_application_namedGauge1").help,207 is("Generated from Dropwizard metric import (metric=my.application.namedGauge1, type=io.prometheus.client.dropwizard.DropwizardExportsTest$ExampleDoubleGauge)"));208 }209 @Test210 public void testThatMetricsMappedToSameNameAreGroupedInSameFamily() {211 final Collector.MetricFamilySamples.Sample namedTimerSample1 = new Collector.MetricFamilySamples.Sample("my_application_namedTimer", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234);212 Mockito.when(sampleBuilder.createSample(eq("my.application.namedTimer1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))213 .thenReturn(namedTimerSample1);214 final Collector.MetricFamilySamples.Sample namedTimerSample2 = new Collector.MetricFamilySamples.Sample("my_application_namedTimer", Collections.<String>emptyList(), Collections.<String>emptyList(), 1235);215 Mockito.when(sampleBuilder.createSample(eq("my.application.namedTimer2"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))216 .thenReturn(namedTimerSample2);217 final Collector.MetricFamilySamples.Sample namedCounter1 = new Collector.MetricFamilySamples.Sample("my_application_namedCounter", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234);218 Mockito.when(sampleBuilder.createSample(eq("my.application.namedCounter1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))219 .thenReturn(namedCounter1);220 final Collector.MetricFamilySamples.Sample namedCounter2 = new Collector.MetricFamilySamples.Sample("my_application_namedCounter", Collections.<String>emptyList(), Collections.<String>emptyList(), 1235);221 Mockito.when(sampleBuilder.createSample(eq("my.application.namedCounter2"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))222 .thenReturn(namedCounter2);223 final Collector.MetricFamilySamples.Sample namedMeter1 = new Collector.MetricFamilySamples.Sample("my_application_namedMeter_total", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234);224 Mockito.when(sampleBuilder.createSample(eq("my.application.namedMeter1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))225 .thenReturn(namedMeter1);226 final Collector.MetricFamilySamples.Sample namedMeter2 = new Collector.MetricFamilySamples.Sample("my_application_namedMeter_total", Collections.<String>emptyList(), Collections.<String>emptyList(), 1235);227 Mockito.when(sampleBuilder.createSample(eq("my.application.namedMeter2"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))228 .thenReturn(namedMeter2);229 final Collector.MetricFamilySamples.Sample namedHistogram1 = new Collector.MetricFamilySamples.Sample("my_application_namedHistogram", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234);230 Mockito.when(sampleBuilder.createSample(eq("my.application.namedHistogram1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))231 .thenReturn(namedHistogram1);232 final Collector.MetricFamilySamples.Sample namedHistogram2 = new Collector.MetricFamilySamples.Sample("my_application_namedHistogram", Collections.<String>emptyList(), Collections.<String>emptyList(), 1235);233 Mockito.when(sampleBuilder.createSample(eq("my.application.namedHistogram2"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))234 .thenReturn(namedHistogram2);235 final Collector.MetricFamilySamples.Sample namedGauge1 = new Collector.MetricFamilySamples.Sample("my_application_namedGauge", Collections.<String>emptyList(), Collections.<String>emptyList(), 1234);236 Mockito.when(sampleBuilder.createSample(eq("my.application.namedGauge1"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))237 .thenReturn(namedGauge1);238 final Collector.MetricFamilySamples.Sample namedGauge2 = new Collector.MetricFamilySamples.Sample("my_application_namedGauge", Collections.<String>emptyList(), Collections.<String>emptyList(), 1235);239 Mockito.when(sampleBuilder.createSample(eq("my.application.namedGauge2"), anyString(), anyListOf(String.class), anyListOf(String.class), anyDouble()))240 .thenReturn(namedGauge2);241 metricRegistry.timer("my.application.namedTimer1");242 metricRegistry.timer("my.application.namedTimer2");243 metricRegistry.counter("my.application.namedCounter1");244 metricRegistry.counter("my.application.namedCounter2");245 metricRegistry.meter("my.application.namedMeter1");246 metricRegistry.meter("my.application.namedMeter2");247 metricRegistry.histogram("my.application.namedHistogram1");248 metricRegistry.histogram("my.application.namedHistogram2");249 metricRegistry.register("my.application.namedGauge1", new ExampleDoubleGauge());250 metricRegistry.register("my.application.namedGauge2", new ExampleDoubleGauge());251 Enumeration<Collector.MetricFamilySamples> metricFamilySamples = registry.metricFamilySamples();252 Map<String, Collector.MetricFamilySamples> elements = new HashMap<String, Collector.MetricFamilySamples>();253 while (metricFamilySamples.hasMoreElements()) {...
Source:AngularMapOntologyControllerTest.java
...86 final VariableDTO entryTypeVariable = new VariableDTO();87 entryTypeVariable.setHeaderName(TermId.ENTRY_TYPE.name());88 entryTypeVariable.setId(TermId.ENTRY_TYPE.getId());89 //90 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.LOCATION_ID.getId()), ArgumentMatchers.anyListOf(91 MeasurementVariable.class))).thenReturn(Optional.absent());92 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.TRIAL_LOCATION.getId()), ArgumentMatchers.anyListOf(93 MeasurementVariable.class))).thenReturn(Optional.of(new MeasurementVariable()));94 final VariableDTO[] variables = { variableWithNoHeaderMapping, variableDuplicate1, variableDuplicate2, entryTypeVariable } ;95 this.controller.processImport(variables);96 final ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);97 Mockito.verify(this.etlService).mergeVariableData(variables, this.userSelection, true);98 Mockito.verify(this.etlService).validateProjectOntology(workbook);99 Mockito.verify(this.etlService, Mockito.times(6)).convertMessageList(captor.capture());100 final List<List> messages = captor.getAllValues();101 final List<String> messageKeys = new ArrayList<>();102 for (final List<Message> message : messages) {103 messageKeys.add(message.get(0).getMessageKey());104 }105 Assert.assertTrue(messageKeys.contains(AngularMapOntologyController.ERROR_HEADER_NO_MAPPING));106 Assert.assertTrue(messageKeys.contains(AngularMapOntologyController.ERROR_DUPLICATE_LOCAL_VARIABLE));107 Assert.assertTrue(messageKeys.contains(AngularMapOntologyController.ERROR_LOCATION_ID_DOESNT_EXISTS));108 Assert.assertTrue(messageKeys.contains(AngularMapOntologyController.INVALID_MEANS_IMPORT_VARIABLE));109 }110 @Test111 public void testProcessImporHeaderSuccess() throws IOException, WorkbookParserException {112 final org.apache.poi.ss.usermodel.Workbook apacheWorkbook = Mockito113 .mock(org.apache.poi.ss.usermodel.Workbook.class);114 final Workbook workbook = WorkbookTestDataInitializer.createTestWorkbook(1, new StudyTypeDto(TRIAL_TYPE_ID,"","T"), "Sample Study", 1,115 false);116 Mockito.when(this.etlService.retrieveCurrentWorkbook(this.userSelection)).thenReturn(apacheWorkbook);117 Mockito.when(this.etlService.convertToWorkbook(this.userSelection)).thenReturn(workbook);118 Mockito.when(this.dataImportService.parseWorkbookDescriptionSheet(apacheWorkbook, CURRENT_IBDB_USER_ID)).thenReturn(workbook);119 final VariableDTO variable1 = new VariableDTO();120 variable1.setId(101);121 variable1.setHeaderName("VARIABLE1");122 final VariableDTO variable2 = new VariableDTO();123 variable2.setId(102);124 variable2.setHeaderName("VARIABLE2");125 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.LOCATION_ID.getId()), ArgumentMatchers.anyListOf(126 MeasurementVariable.class))).thenReturn(Optional.of(new MeasurementVariable()));127 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.TRIAL_LOCATION.getId()), ArgumentMatchers.anyListOf(128 MeasurementVariable.class))).thenReturn(Optional.of(new MeasurementVariable()));129 final VariableDTO[] variables = { variable1, variable2 } ;130 this.controller.processImport(variables);131 Mockito.verify(this.etlService).mergeVariableData(variables, this.userSelection, true);132 Mockito.verify(this.etlService).validateProjectOntology(workbook);133 Mockito.verify(this.etlService, Mockito.times(0)).convertMessageList(Mockito.anyListOf(Message.class));134 }135 @Test136 public void testProcessInvalidTrialInstanceValue() throws IOException, WorkbookParserException {137 final org.apache.poi.ss.usermodel.Workbook apacheWorkbook = Mockito138 .mock(org.apache.poi.ss.usermodel.Workbook.class);139 final Workbook workbook = WorkbookTestDataInitializer.createTestWorkbook(1, new StudyTypeDto(TRIAL_TYPE_ID,"","T"), "Sample Study", 1,140 false);141 // Replace Value of Trial Instance142 for (final MeasurementVariable var : workbook.getConditions()) {143 if (var.getTermId() == TermId.TRIAL_INSTANCE_FACTOR.getId()) {144 var.setValue("a");145 }146 }147 Mockito.when(this.etlService.retrieveCurrentWorkbook(this.userSelection)).thenReturn(apacheWorkbook);148 Mockito.when(this.etlService.convertToWorkbook(this.userSelection)).thenReturn(workbook);149 Mockito.when(this.dataImportService.parseWorkbookDescriptionSheet(apacheWorkbook, CURRENT_IBDB_USER_ID)).thenReturn(workbook);150 final VariableDTO variable1 = new VariableDTO();151 variable1.setId(101);152 variable1.setHeaderName("VARIABLE1");153 final VariableDTO variable2 = new VariableDTO();154 variable2.setId(102);155 variable2.setHeaderName("VARIABLE2");156 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.LOCATION_ID.getId()), ArgumentMatchers.anyListOf(157 MeasurementVariable.class))).thenReturn(Optional.of(new MeasurementVariable()));158 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.TRIAL_LOCATION.getId()), ArgumentMatchers.anyListOf(159 MeasurementVariable.class))).thenReturn(Optional.of(new MeasurementVariable()));160 final VariableDTO[] variables = { variable1, variable2 } ;161 this.controller.processImport(variables);162 Mockito.verify(this.etlService).mergeVariableData(variables, this.userSelection, true);163 Mockito.verify(this.etlService).validateProjectOntology(workbook);164 // With Error165 Mockito.verify(this.etlService, Mockito.times(1)).convertMessageList(Mockito.anyListOf(Message.class));166 final Map<String, List<Message>> errorMessages = new HashMap<>();167 this.controller.validateTrialInstanceValue(workbook.getConditions(), errorMessages);168 Assert.assertTrue("Invalid Trial Error",errorMessages.containsKey(Constants.INVALID_TRIAL));169 Assert.assertEquals("Single Error",1, errorMessages.get(Constants.INVALID_TRIAL).size());170 }171 @Test172 public void testConfirmImport() throws IOException, WorkbookParserException {173 final org.apache.poi.ss.usermodel.Workbook apacheWorkbook = Mockito174 .mock(org.apache.poi.ss.usermodel.Workbook.class);175 final Workbook workbook = WorkbookTestDataInitializer.createTestWorkbook(1, new StudyTypeDto(TRIAL_TYPE_ID,"","T"), "Sample Study", 1,176 false);177 workbook.getStudyDetails().getStudyType().setId(1);178 Mockito.when(this.etlService.retrieveCurrentWorkbook(this.userSelection)).thenReturn(apacheWorkbook);179 Mockito.when(this.etlService.convertToWorkbook(this.userSelection)).thenReturn(workbook);180 Mockito.when(this.dataImportService.parseWorkbookDescriptionSheet(apacheWorkbook, CURRENT_IBDB_USER_ID)).thenReturn(workbook);181 final VariableDTO[] variables = new VariableDTO[] {};182 final Map<String, Object> result = this.controller.confirmImport(variables, true, this.session, this.request);183 Mockito.verify(this.userSelection).clearMeasurementVariables();184 Mockito.verify(this.etlService).mergeVariableData(variables, this.userSelection, true);185 Mockito.verify(this.dataImportService).addLocationIDVariableIfNotExists(workbook, workbook.getFactors(), PROGRAM_UUID);186 Mockito.verify(this.dataImportService).addEntryTypeVariableIfNotExists(workbook, PROGRAM_UUID);187 Mockito.verify(this.dataImportService).assignLocationIdVariableToEnvironmentDetailSection(workbook);188 Mockito.verify(this.dataImportService).removeLocationNameVariableIfExists(workbook);189 Mockito.verify(this.fieldbookService).addStudyUUIDConditionAndObsUnitIDFactorToWorkbook(workbook, false);190 Mockito.verify(this.etlService).saveProjectOntology(workbook, AngularMapOntologyControllerTest.PROGRAM_UUID);191 Mockito.verify(this.userSelection).setStudyId(workbook.getStudyDetails().getId());192 Mockito.verify(this.userSelection).setTrialDatasetId(workbook.getTrialDatasetId());193 Mockito.verify(this.userSelection).setMeasurementDatasetId(workbook.getMeasurementDatesetId());194 Mockito.verify(this.userSelection).setMeansDatasetId(workbook.getMeansDatasetId());195 Assert.assertEquals(true, result.get("success"));196 Assert.assertEquals(AngularMapOntologyControllerTest.CONTEXT_PATH + AngularOpenSheetController.URL,197 result.get("redirectUrl"));198 }199 @Test200 public void testProcessExperimentalDesign() throws WorkbookParserException {201 final Workbook importData = new Workbook();202 final org.apache.poi.ss.usermodel.Workbook workbook = Mockito.mock(org.apache.poi.ss.usermodel.Workbook.class);203 final List<String> headers = Arrays.asList("EXPT_DESIGN", "DESIG");204 Mockito.when(this.etlService.retrieveColumnHeaders(workbook, this.userSelection, false)).thenReturn(headers);205 final List<MeasurementVariable> factors = new ArrayList<>();206 factors.add(MeasurementVariableTestDataInitializer.createMeasurementVariable(TermId.EXPERIMENT_DESIGN_FACTOR.getId(), "EXPT_DESIGN","RCBD"));207 importData.setFactors(factors);208 final String valueFromObsevations = "RCBD";209 Mockito.when(this.etlService.getExperimentalDesignValueFromObservationSheet(workbook, this.userSelection, 0)).thenReturn(valueFromObsevations);210 this.controller.processExperimentalDesign(importData, workbook);211 Mockito.verify(this.etlService).retrieveColumnHeaders(workbook, this.userSelection, false);212 Mockito.verify(this.etlService).getExperimentalDesignValueFromObservationSheet(workbook, this.userSelection, 0);213 Mockito.verify(this.dataImportService).processExperimentalDesign(importData, this.contextUtil.getCurrentProgramUUID(), valueFromObsevations);214 }215 @Test216 public void testCheckIfLocationIdVariableExists() throws IOException, WorkbookParserException {217 final org.apache.poi.ss.usermodel.Workbook apacheWorkbook = Mockito218 .mock(org.apache.poi.ss.usermodel.Workbook.class);219 final Workbook workbook = WorkbookTestDataInitializer.createTestWorkbook(6, new StudyTypeDto(TRIAL_TYPE_ID,"","T"), "Sample Study", 1,220 false);221 Mockito.when(this.etlService.retrieveCurrentWorkbook(this.userSelection)).thenReturn(apacheWorkbook);222 Mockito.when(this.dataImportService.parseWorkbookDescriptionSheet(apacheWorkbook, CURRENT_IBDB_USER_ID)).thenReturn(workbook);223 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.LOCATION_ID.getId()), ArgumentMatchers.anyListOf(224 MeasurementVariable.class))).thenReturn(Optional.absent());225 Mockito.when(this.dataImportService.findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.TRIAL_LOCATION.getId()), ArgumentMatchers.anyListOf(226 MeasurementVariable.class))).thenReturn(Optional.of(new MeasurementVariable()));227 Assert.assertTrue(this.controller.checkIfLocationIdVariableExists(workbook));228 final ArgumentCaptor<List> captor1 = ArgumentCaptor.forClass(List.class);229 final ArgumentCaptor<List> captor2 = ArgumentCaptor.forClass(List.class);230 Mockito.verify(this.dataImportService).findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.LOCATION_ID.getId()), captor1.capture());231 Mockito.verify(this.dataImportService).findMeasurementVariableByTermId(ArgumentMatchers.eq(TermId.LOCATION_ID.getId()), captor2.capture());232 final List<MeasurementVariable> measurementVariables = new ArrayList<>();233 measurementVariables.addAll(workbook.getConditions());234 measurementVariables.addAll(workbook.getFactors());235 Assert.assertEquals(measurementVariables, captor1.getValue());236 Assert.assertEquals(measurementVariables, captor2.getValue());237 }238}...
Source:FeedActionReaderTest.java
...4package org.chromium.chrome.browser.feed.library.feedactionreader;5import static com.google.common.truth.Truth.assertThat;6import static org.mockito.ArgumentMatchers.anyDouble;7import static org.mockito.ArgumentMatchers.anyList;8import static org.mockito.ArgumentMatchers.anyListOf;9import static org.mockito.ArgumentMatchers.anyLong;10import static org.mockito.ArgumentMatchers.eq;11import static org.mockito.ArgumentMatchers.same;12import static org.mockito.Mockito.never;13import static org.mockito.Mockito.verify;14import static org.mockito.Mockito.when;15import static org.mockito.MockitoAnnotations.initMocks;16import org.junit.Before;17import org.junit.Test;18import org.junit.runner.RunWith;19import org.mockito.Mock;20import org.robolectric.annotation.Config;21import org.chromium.chrome.browser.feed.library.api.host.config.Configuration;22import org.chromium.chrome.browser.feed.library.api.host.config.Configuration.ConfigKey;23import org.chromium.chrome.browser.feed.library.api.internal.actionmanager.ActionReader;24import org.chromium.chrome.browser.feed.library.api.internal.common.DismissActionWithSemanticProperties;25import org.chromium.chrome.browser.feed.library.api.internal.common.SemanticPropertiesWithId;26import org.chromium.chrome.browser.feed.library.api.internal.common.testing.ContentIdGenerators;27import org.chromium.chrome.browser.feed.library.api.internal.protocoladapter.ProtocolAdapter;28import org.chromium.chrome.browser.feed.library.api.internal.store.LocalActionMutation.ActionType;29import org.chromium.chrome.browser.feed.library.api.internal.store.Store;30import org.chromium.chrome.browser.feed.library.common.Result;31import org.chromium.chrome.browser.feed.library.common.concurrent.testing.FakeTaskQueue;32import org.chromium.chrome.browser.feed.library.common.concurrent.testing.FakeThreadUtils;33import org.chromium.chrome.browser.feed.library.common.testing.ResponseBuilder;34import org.chromium.chrome.browser.feed.library.common.time.testing.FakeClock;35import org.chromium.components.feed.core.proto.libraries.api.internal.StreamDataProto.StreamLocalAction;36import org.chromium.components.feed.core.proto.wire.ContentIdProto.ContentId;37import org.chromium.testing.local.LocalRobolectricTestRunner;38import java.util.Arrays;39import java.util.Collections;40import java.util.List;41import java.util.concurrent.TimeUnit;42/** Tests of the {@link FeedActionReader} class. */43@RunWith(LocalRobolectricTestRunner.class)44@Config(manifest = Config.NONE)45public class FeedActionReaderTest {46 private static final ContentIdGenerators ID_GENERATOR = new ContentIdGenerators();47 private static final ContentId CONTENT_ID = ResponseBuilder.createFeatureContentId(1);48 private static final String CONTENT_ID_STRING = ID_GENERATOR.createContentId(CONTENT_ID);49 private static final ContentId CONTENT_ID_2 = ResponseBuilder.createFeatureContentId(2);50 private static final String CONTENT_ID_STRING_2 = ID_GENERATOR.createContentId(CONTENT_ID_2);51 private static final long DEFAULT_TIME = TimeUnit.DAYS.toSeconds(42);52 private final FakeClock mFakeClock = new FakeClock();53 private final FakeThreadUtils mFakeThreadUtils = FakeThreadUtils.withThreadChecks();54 @Mock55 private Store mStore;56 @Mock57 private ProtocolAdapter mProtocolAdapter;58 @Mock59 private Configuration mConfiguration;60 private ActionReader mActionReader;61 @Before62 public void setUp() throws Exception {63 initMocks(this);64 when(mConfiguration.getValueOrDefault(65 same(ConfigKey.DEFAULT_ACTION_TTL_SECONDS), anyLong()))66 .thenReturn(TimeUnit.DAYS.toSeconds(3));67 when(mConfiguration.getValueOrDefault(68 same(ConfigKey.MINIMUM_VALID_ACTION_RATIO), anyDouble()))69 .thenReturn(0.9);70 when(mStore.triggerLocalActionGc(71 anyListOf(StreamLocalAction.class), anyListOf(String.class)))72 .thenReturn(() -> {});73 mActionReader = new FeedActionReader(74 mStore, mFakeClock, mProtocolAdapter, getTaskQueue(), mConfiguration);75 when(mProtocolAdapter.getWireContentId(CONTENT_ID_STRING))76 .thenReturn(Result.success(CONTENT_ID));77 when(mProtocolAdapter.getWireContentId(CONTENT_ID_STRING_2))78 .thenReturn(Result.success(CONTENT_ID_2));79 }80 @Test81 public void getAllDismissedActions() {82 mFakeClock.set(DEFAULT_TIME);83 StreamLocalAction dismissAction = buildDismissAction(CONTENT_ID_STRING);84 mockStoreCalls(Collections.singletonList(dismissAction), Collections.emptyList());85 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =86 mActionReader.getDismissActionsWithSemanticProperties();87 assertThat(dismissActionsResult.isSuccessful()).isTrue();88 List<DismissActionWithSemanticProperties> dismissActions = dismissActionsResult.getValue();89 assertThat(dismissActions)90 .containsExactly(new DismissActionWithSemanticProperties(CONTENT_ID, null));91 }92 @Test93 public void getAllDismissedActions_empty() {94 mFakeClock.set(DEFAULT_TIME);95 mockStoreCalls(Collections.emptyList(), Collections.emptyList());96 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =97 mActionReader.getDismissActionsWithSemanticProperties();98 assertThat(dismissActionsResult.isSuccessful()).isTrue();99 List<DismissActionWithSemanticProperties> dismissActions = dismissActionsResult.getValue();100 assertThat(dismissActions).hasSize(0);101 verify(mStore, never())102 .triggerLocalActionGc(anyListOf(StreamLocalAction.class), anyListOf(String.class));103 }104 @Test105 public void getAllDismissedActions_storeError_getAllDismissActions() {106 mFakeClock.set(DEFAULT_TIME);107 when(mStore.getAllDismissLocalActions()).thenReturn(Result.failure());108 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =109 mActionReader.getDismissActionsWithSemanticProperties();110 assertThat(dismissActionsResult.isSuccessful()).isFalse();111 verify(mStore, never())112 .triggerLocalActionGc(anyListOf(StreamLocalAction.class), anyListOf(String.class));113 }114 @Test115 public void getAllDismissedActions_storeError_getSemanticProperties() {116 mFakeClock.set(DEFAULT_TIME);117 StreamLocalAction dismissAction = buildDismissAction(CONTENT_ID_STRING);118 when(mStore.getAllDismissLocalActions())119 .thenReturn(Result.success(Collections.singletonList(dismissAction)));120 when(mStore.getSemanticProperties(anyList())).thenReturn(Result.failure());121 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =122 mActionReader.getDismissActionsWithSemanticProperties();123 assertThat(dismissActionsResult.isSuccessful()).isFalse();124 verify(mStore, never())125 .triggerLocalActionGc(anyListOf(StreamLocalAction.class), anyListOf(String.class));126 }127 @Test128 public void getAllDismissedActions_expired() {129 mFakeClock.set(TimeUnit.SECONDS.toMillis(DEFAULT_TIME) + TimeUnit.DAYS.toMillis(3));130 StreamLocalAction dismissAction = buildDismissAction(CONTENT_ID_STRING);131 List<StreamLocalAction> dismissActions = Collections.singletonList(dismissAction);132 mockStoreCalls(dismissActions, Collections.emptyList());133 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =134 mActionReader.getDismissActionsWithSemanticProperties();135 assertThat(dismissActionsResult.isSuccessful()).isTrue();136 assertThat(dismissActionsResult.getValue()).hasSize(0);137 verify(mStore).triggerLocalActionGc(eq(dismissActions), anyListOf(String.class));138 }139 @Test140 public void getAllDismissedActions_semanticProperties() {141 mFakeClock.set(DEFAULT_TIME);142 StreamLocalAction dismissAction = buildDismissAction(CONTENT_ID_STRING);143 byte[] semanticData = {12, 41};144 mockStoreCalls(Collections.singletonList(dismissAction),145 Collections.singletonList(146 new SemanticPropertiesWithId(CONTENT_ID_STRING, semanticData)));147 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =148 mActionReader.getDismissActionsWithSemanticProperties();149 assertThat(dismissActionsResult.isSuccessful()).isTrue();150 List<DismissActionWithSemanticProperties> dismissActions = dismissActionsResult.getValue();151 assertThat(dismissActions)152 .containsExactly(new DismissActionWithSemanticProperties(CONTENT_ID, semanticData));153 verify(mStore, never())154 .triggerLocalActionGc(anyListOf(StreamLocalAction.class), anyListOf(String.class));155 }156 @Test157 public void getAllDismissedActions_multipleActions() {158 mFakeClock.set(DEFAULT_TIME);159 StreamLocalAction dismissAction = buildDismissAction(CONTENT_ID_STRING);160 StreamLocalAction dismissAction2 = buildDismissAction(CONTENT_ID_STRING_2);161 mockStoreCalls(Arrays.asList(dismissAction, dismissAction2), Collections.emptyList());162 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =163 mActionReader.getDismissActionsWithSemanticProperties();164 assertThat(dismissActionsResult.isSuccessful()).isTrue();165 List<DismissActionWithSemanticProperties> dismissActions = dismissActionsResult.getValue();166 assertThat(dismissActions)167 .containsExactly(new DismissActionWithSemanticProperties(CONTENT_ID, null),168 new DismissActionWithSemanticProperties(CONTENT_ID_2, null));169 verify(mStore, never())170 .triggerLocalActionGc(anyListOf(StreamLocalAction.class), anyListOf(String.class));171 }172 @Test173 public void getAllDismissedActions_multipleActions_semanticProperties() {174 mFakeClock.set(DEFAULT_TIME);175 StreamLocalAction dismissAction = buildDismissAction(CONTENT_ID_STRING);176 StreamLocalAction dismissAction2 = buildDismissAction(CONTENT_ID_STRING_2);177 byte[] semanticData = {12, 41};178 byte[] semanticData2 = {42, 72};179 mockStoreCalls(Arrays.asList(dismissAction, dismissAction2),180 Arrays.asList(new SemanticPropertiesWithId(CONTENT_ID_STRING, semanticData),181 new SemanticPropertiesWithId(CONTENT_ID_STRING_2, semanticData2)));182 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =183 mActionReader.getDismissActionsWithSemanticProperties();184 assertThat(dismissActionsResult.isSuccessful()).isTrue();185 List<DismissActionWithSemanticProperties> dismissActions = dismissActionsResult.getValue();186 assertThat(dismissActions)187 .containsExactly(new DismissActionWithSemanticProperties(CONTENT_ID, semanticData),188 new DismissActionWithSemanticProperties(CONTENT_ID_2, semanticData2));189 verify(mStore, never())190 .triggerLocalActionGc(anyListOf(StreamLocalAction.class), anyListOf(String.class));191 }192 @Test193 public void getAllDismissedActions_multipleActions_someExpired() {194 mFakeClock.set(TimeUnit.SECONDS.toMillis(DEFAULT_TIME) + TimeUnit.DAYS.toMillis(3));195 StreamLocalAction dismissAction = buildDismissAction(CONTENT_ID_STRING);196 StreamLocalAction dismissAction2 =197 StreamLocalAction.newBuilder()198 .setAction(ActionType.DISMISS)199 .setFeatureContentId(CONTENT_ID_STRING_2)200 .setTimestampSeconds(DEFAULT_TIME + TimeUnit.DAYS.toSeconds(2))201 .build();202 mockStoreCalls(Arrays.asList(dismissAction, dismissAction2), Collections.emptyList());203 Result<List<DismissActionWithSemanticProperties>> dismissActionsResult =204 mActionReader.getDismissActionsWithSemanticProperties();...
Source:TagsPresenterTest.java
...19import rx.Observable;20import static junit.framework.TestCase.assertNotNull;21import static org.mockito.ArgumentMatchers.any;22import static org.mockito.ArgumentMatchers.anyInt;23import static org.mockito.ArgumentMatchers.anyListOf;24import static org.mockito.ArgumentMatchers.anyString;25import static org.mockito.ArgumentMatchers.eq;26import static org.mockito.Mockito.never;27import static org.mockito.Mockito.times;28/**29 * @author Artur Vasilov30 */31@RunWith(JUnit4.class)32public class TagsPresenterTest {33 private static final String FOUND_TAGS_KEY = "found_tags";34 private static final String FIRST_VISIBLE_ITEM_KEY = "first_visible_item_key";35 private TagsView mView;36 private LoadingView mLoadingView;37 private TagsPresenter mPresenter;38 @Before39 public void setUp() throws Exception {40 mView = Mockito.mock(TagsView.class);41 Mockito.doNothing().when(mView).clearText();42 Mockito.doNothing().when(mView).setEmptyText(anyInt());43 Mockito.doNothing().when(mView).hideAllElements();44 Mockito.doNothing().when(mView).showTags(anyListOf(Tag.class));45 Mockito.doNothing().when(mView).showFirstVisibleItem(anyInt());46 Mockito.doNothing().when(mView).showClearButton();47 Mockito.doNothing().when(mView).hideClearButton();48 Mockito.doNothing().when(mView).notifyChanged();49 Mockito.doNothing().when(mView).showEmptyListView();50 Mockito.doNothing().when(mView).hideEmptyListView();51 mLoadingView = Mockito.mock(LoadingView.class);52 mPresenter = new TagsPresenter(MockUtils.mockContext(), MockUtils.mockLoaderManager(),53 mView, mLoadingView);54 RepositoryProvider.setRemoteRepository(new TestRemoteRepository());55 RepositoryProvider.setLocalRepository(new TestLocalRepository());56 }57 @Test58 public void testCreated() throws Exception {59 assertNotNull(mPresenter);60 }61 @Test62 public void testInitEmpty() throws Exception {63 mPresenter.init(null);64 Mockito.verify(mView).hideAllElements();65 }66 @Test67 public void testShowSavedTags() throws Exception {68 RepositoryProvider.setLocalRepository(new ContentLocalRepository(false));69 mPresenter.init(null);70 Mockito.verify(mView).showTags(anyListOf(Tag.class));71 Mockito.verify(mView).hideEmptyListView();72 Mockito.verify(mView).hideClearButton();73 Mockito.verify(mView).showFirstVisibleItem(0);74 }75 @Test76 public void testEmptyInputNoFavourite() throws Exception {77 mPresenter.init(null);78 mPresenter.onInput("");79 Mockito.verify(mView, times(2)).hideAllElements();80 }81 @Test82 public void testEmptyInputSavedFavourite() throws Exception {83 RepositoryProvider.setLocalRepository(new ContentLocalRepository(false));84 mPresenter.init(null);85 mPresenter.onInput("");86 Mockito.verify(mView, times(2)).showTags(anyListOf(Tag.class));87 Mockito.verify(mView, times(2)).hideEmptyListView();88 Mockito.verify(mView, times(2)).hideClearButton();89 Mockito.verify(mLoadingView).hideLoadingIndicator();90 }91 @Test92 public void testOnEmptyClick() throws Exception {93 mPresenter.init(null);94 mPresenter.onInput("a");95 mPresenter.onClearButtonClick();96 Mockito.verify(mView).clearText();97 Mockito.verify(mView, times(2)).hideAllElements();98 }99 @Test100 public void testLoadingShown() throws Exception {101 mPresenter.init(null);102 mPresenter.onInput("a");103 Mockito.verify(mLoadingView).showLoadingIndicator();104 Mockito.verify(mLoadingView).hideLoadingIndicator();105 }106 @Test107 public void testContentShown() throws Exception {108 RepositoryProvider.setRemoteRepository(new ContentRemoteRepository());109 mPresenter.init(null);110 mPresenter.onInput("a");111 Mockito.verify(mView).showTags(anyListOf(Tag.class));112 }113 @Test114 public void testFavouriteReplaced() throws Exception {115 RepositoryProvider.setLocalRepository(new ContentLocalRepository(false));116 RepositoryProvider.setRemoteRepository(new ContentRemoteRepository());117 mPresenter.init(null);118 mPresenter.onInput("a");119 Mockito.verify(mView, times(2)).showTags(anyListOf(Tag.class));120 }121 @Test122 public void testEmptyListShown() throws Exception {123 mPresenter.init(null);124 mPresenter.onInput("0");125 Mockito.verify(mView).showEmptyListView();126 Mockito.verify(mView, never()).showTags(anyListOf(Tag.class));127 }128 @Test129 public void testAddTagToFavourite() throws Exception {130 RepositoryProvider.setLocalRepository(new ContentLocalRepository(true));131 RepositoryProvider.setRemoteRepository(new ContentRemoteRepository());132 mPresenter.init(null);133 mPresenter.onInput("a");134 mPresenter.onFavouriteClick(1);135 Mockito.verify(mView).notifyChanged();136 }137 @Test138 public void testRemoveTagFromFavourite() throws Exception {139 RepositoryProvider.setLocalRepository(new ContentLocalRepository(false));140 mPresenter.init(null);141 mPresenter.onFavouriteClick(0);142 Mockito.verify(mView).notifyChanged();143 }144 @SuppressWarnings("unchecked")145 @Test146 public void testStateSaved() throws Exception {147 RepositoryProvider.setLocalRepository(new ContentLocalRepository(false));148 mPresenter.init(null);149 Bundle outState = Mockito.mock(Bundle.class);150 Mockito.doNothing().when(outState).putParcelableArrayList(anyString(), any(ArrayList.class));151 Mockito.doNothing().when(outState).putInt(anyString(), anyInt());152 mPresenter.onSaveInstanceState(outState, 1);153 Mockito.verify(outState).putInt(FIRST_VISIBLE_ITEM_KEY, 1);154 Mockito.verify(outState).putParcelableArrayList(eq(FOUND_TAGS_KEY), any(ArrayList.class));155 }156 @SuppressWarnings("unchecked")157 @Test158 public void testPositionRestored() throws Exception {159 ArrayList tags = new ArrayList();160 tags.add(new Tag("android", false));161 tags.add(new Tag("android-actionbar", false));162 tags.add(new Tag("android-testing", false));163 tags.add(new Tag("java", false));164 Bundle savedInstanceState = Mockito.mock(Bundle.class);165 Mockito.when(savedInstanceState.getParcelableArrayList(FOUND_TAGS_KEY)).thenReturn(tags);166 Mockito.when(savedInstanceState.getInt(FIRST_VISIBLE_ITEM_KEY)).thenReturn(2);167 mPresenter.init(savedInstanceState);168 Mockito.verify(mView).showFirstVisibleItem(2);169 }170 @SuppressWarnings("unchecked")171 @Test172 public void testFoundTagsRestored() throws Exception {173 ArrayList tags = new ArrayList();174 tags.add(new Tag("android-actionbar", false));175 tags.add(new Tag("java", false));176 Bundle savedInstanceState = Mockito.mock(Bundle.class);177 Mockito.when(savedInstanceState.getParcelableArrayList(FOUND_TAGS_KEY)).thenReturn(tags);178 Mockito.when(savedInstanceState.getInt(FIRST_VISIBLE_ITEM_KEY)).thenReturn(1);179 mPresenter.init(savedInstanceState);180 Mockito.verify(mView).showTags(anyListOf(Tag.class));181 Mockito.verify(mView).hideEmptyListView();182 Mockito.verify(mView).showClearButton();183 }184 @SuppressWarnings("ConstantConditions")185 @After186 public void tearDown() throws Exception {187 RepositoryProvider.setRemoteRepository(null);188 RepositoryProvider.setLocalRepository(null);189 }190 private class ContentLocalRepository extends TestLocalRepository {191 private final boolean mUpdateResult;192 public ContentLocalRepository(boolean updateResult) {193 mUpdateResult = updateResult;194 }...
Source:ProfilePresenterTest.java
...25import rx.Observable;26import static junit.framework.TestCase.assertNotNull;27import static org.mockito.ArgumentMatchers.anyBoolean;28import static org.mockito.ArgumentMatchers.anyInt;29import static org.mockito.ArgumentMatchers.anyListOf;30import static org.mockito.ArgumentMatchers.anyString;31import static org.mockito.ArgumentMatchers.eq;32import static org.mockito.Mockito.times;33/**34 * @author Artur Vasilov35 */36@RunWith(JUnit4.class)37public class ProfilePresenterTest {38 private static final String ERROR_SHOWN_KEY = "error_shown";39 private ProfileView mView;40 private LoadingView mLoadingView;41 private ErrorView mErrorView;42 private ProfilePresenter mPresenter;43 @Before44 public void setUp() throws Exception {45 mView = Mockito.mock(ProfileView.class);46 Mockito.doNothing().when(mView).showUserName(anyString());47 Mockito.doNothing().when(mView).showUserImage(anyString());48 Mockito.doNothing().when(mView).showProfileLink(anyString());49 Mockito.doNothing().when(mView).showReputation(anyString());50 Mockito.doNothing().when(mView).showBadges(anyListOf(Badge.class));51 Mockito.doNothing().when(mView).showTopTags(anyListOf(UserTag.class));52 Context context = Mockito.mock(Context.class);53 Mockito.when(context.getString(eq(R.string.reputation), anyInt())).thenAnswer(invocation -> {54 int reputation = (int) invocation.getArguments()[1];55 return String.format(Locale.getDefault(), "Reputation: %1$d", reputation);56 });57 Mockito.when(context.getString(R.string.profile_text)).thenReturn("Profile");58 mLoadingView = MockUtils.mockLoadingView();59 mErrorView = MockUtils.mockErrorView();60 User user = new User();61 user.setUserId(932123);62 user.setAge(19);63 user.setName("Artur Vasilov");64 user.setReputation(2985);65 user.setLink("http://stackoverflow.com/users/3637200/vasilov-artur");66 user.setProfileImage("https://i.stack.imgur.com/EJNBv.jpg?sz=128&g=1");67 mPresenter = new ProfilePresenter(context, MockUtils.mockLoaderManager(), mView,68 mLoadingView, mErrorView, user);69 RepositoryProvider.setRemoteRepository(new TestRemoteRepository());70 }71 @Test72 public void testCreated() throws Exception {73 assertNotNull(mPresenter);74 }75 @Test76 public void testLoadingProgressShown() throws Exception {77 mPresenter.init(null);78 Mockito.verify(mLoadingView).showLoadingIndicator();79 Mockito.verify(mLoadingView).hideLoadingIndicator();80 }81 @Test82 public void testFullUserInfoShown() throws Exception {83 mPresenter.init(null);84 verifyUserInfoShown();85 }86 @Test87 public void testEmptyBadgesNotShown() throws Exception {88 mPresenter.init(null);89 Mockito.verify(mView, times(0)).showBadges(anyListOf(Badge.class));90 }91 @Test92 public void testEmptyTagsNotShown() throws Exception {93 mPresenter.init(null);94 Mockito.verify(mView, times(0)).showTopTags(anyListOf(UserTag.class));95 }96 @Test97 public void testBadgesAndTagsShown() throws Exception {98 RepositoryProvider.setRemoteRepository(new ContentRepository());99 mPresenter.init(null);100 Mockito.verify(mView).showBadges(anyListOf(Badge.class));101 Mockito.verify(mView).showTopTags(anyListOf(UserTag.class));102 }103 @Test104 public void testErrorShown() throws Exception {105 RepositoryProvider.setRemoteRepository(new ErrorRepository());106 mPresenter.init(null);107 Mockito.verify(mErrorView).showNetworkError();108 }109 @Test110 public void testErrorShownOnlyOnce() throws Exception {111 Bundle savedInstanceState = Mockito.mock(Bundle.class);112 Mockito.when(savedInstanceState.getBoolean(ERROR_SHOWN_KEY)).thenReturn(true);113 RepositoryProvider.setRemoteRepository(new ErrorRepository());114 mPresenter.init(savedInstanceState);115 Mockito.verifyNoMoreInteractions(mErrorView);...
Source:DependencySetAssemblyPhaseTest.java
...16 * KIND, either express or implied. See the License for the17 * specific language governing permissions and limitations18 * under the License.19 */20import static org.mockito.ArgumentMatchers.anyListOf;21import static org.mockito.ArgumentMatchers.eq;22import static org.mockito.ArgumentMatchers.isNull;23import static org.mockito.Mockito.mock;24import static org.mockito.Mockito.verify;25import static org.mockito.Mockito.when;26import java.io.IOException;27import java.util.Collections;28import java.util.LinkedHashMap;29import java.util.Set;30import org.apache.maven.artifact.Artifact;31import org.apache.maven.model.Model;32import org.apache.maven.plugins.assembly.AssemblerConfigurationSource;33import org.apache.maven.plugins.assembly.InvalidAssemblerConfigurationException;34import org.apache.maven.plugins.assembly.archive.ArchiveCreationException;35import org.apache.maven.plugins.assembly.artifact.DependencyResolutionException;36import org.apache.maven.plugins.assembly.artifact.DependencyResolver;37import org.apache.maven.plugins.assembly.format.AssemblyFormattingException;38import org.apache.maven.plugins.assembly.model.Assembly;39import org.apache.maven.plugins.assembly.model.DependencySet;40import org.apache.maven.project.MavenProject;41import org.apache.maven.project.ProjectBuilder;42import org.junit.Before;43import org.junit.Test;44import org.junit.runner.RunWith;45import org.mockito.junit.MockitoJUnitRunner;46@RunWith( MockitoJUnitRunner.class )47public class DependencySetAssemblyPhaseTest48{49 private DependencySetAssemblyPhase phase;50 51 private DependencyResolver dependencyResolver;52 53 @Before54 public void setUp()55 {56 this.dependencyResolver = mock( DependencyResolver.class );57 58 this.phase = new DependencySetAssemblyPhase( mock( ProjectBuilder.class ), dependencyResolver );59 }60 @Test61 public void testExecute_ShouldAddOneDependencyFromProject()62 throws AssemblyFormattingException, ArchiveCreationException, IOException,63 InvalidAssemblerConfigurationException, DependencyResolutionException64 {65 final String outputLocation = "/out";66 final MavenProject project = newMavenProject( "group", "project", "0" );67 Artifact artifact = mock( Artifact.class );68 project.setArtifact( artifact );69 final DependencySet ds = new DependencySet();70 ds.setUseProjectArtifact( false );71 ds.setOutputDirectory( outputLocation );72 ds.setOutputFileNameMapping( "${artifact.artifactId}" );73 ds.setUnpack( false );74 ds.setScope( Artifact.SCOPE_COMPILE );75 ds.setFileMode( Integer.toString( 10, 8 ) );76 final Assembly assembly = new Assembly();77 assembly.setId( "test" );78 assembly.setIncludeBaseDirectory( false );79 assembly.addDependencySet( ds );80 project.setArtifacts( Collections.singleton( artifact ) );81 when( dependencyResolver.resolveDependencySets( eq( assembly ),82 isNull(AssemblerConfigurationSource.class),83 anyListOf( DependencySet.class ) ) ).thenReturn( new LinkedHashMap<DependencySet, Set<Artifact>>() );84 85 this.phase.execute( assembly, null, null );86 // result of easymock migration, should be assert of expected result instead of verifying methodcalls87 verify( dependencyResolver ).resolveDependencySets( eq( assembly ),88 isNull(AssemblerConfigurationSource.class),89 anyListOf( DependencySet.class ) );90 }91 @Test92 public void testExecute_ShouldNotAddDependenciesWhenProjectHasNone()93 throws Exception94 {95 final Assembly assembly = new Assembly();96 assembly.setId( "test" );97 assembly.setIncludeBaseDirectory( false );98 99 when( dependencyResolver.resolveDependencySets( eq( assembly ), 100 isNull( AssemblerConfigurationSource.class ),101 anyListOf( DependencySet.class ) ) ).thenReturn( new LinkedHashMap<DependencySet, Set<Artifact>>() );102 this.phase.execute( assembly, null, null );103 // result of easymock migration, should be assert of expected result instead of verifying methodcalls104 verify( dependencyResolver ).resolveDependencySets( eq( assembly ),105 isNull( AssemblerConfigurationSource.class ),106 anyListOf( DependencySet.class ) ); 107 }108 109 private MavenProject newMavenProject( final String groupId, final String artifactId, final String version )110 {111 final Model model = new Model();112 model.setGroupId( groupId );113 model.setArtifactId( artifactId );114 model.setVersion( version );115 return new MavenProject( model );116 }117}...
Source:WriterTest.java
1package com.github.ksprojects.zkcopy.writer;2import static org.mockito.ArgumentMatchers.any;3import static org.mockito.ArgumentMatchers.anyBoolean;4import static org.mockito.ArgumentMatchers.anyInt;5import static org.mockito.ArgumentMatchers.anyListOf;6import static org.mockito.ArgumentMatchers.anyString;7import static org.mockito.ArgumentMatchers.eq;8import static org.mockito.ArgumentMatchers.nullable;9import static org.mockito.ArgumentMatchers.startsWith;10import static org.mockito.Mockito.mock;11import static org.mockito.Mockito.times;12import static org.mockito.Mockito.verify;13import static org.mockito.Mockito.verifyNoMoreInteractions;14import static org.mockito.Mockito.when;15import com.github.ksprojects.zkcopy.Node;16import java.util.Arrays;17import org.apache.zookeeper.CreateMode;18import org.apache.zookeeper.KeeperException;19import org.apache.zookeeper.Transaction;20import org.apache.zookeeper.ZooKeeper;21import org.apache.zookeeper.data.ACL;22import org.apache.zookeeper.data.Stat;23import org.junit.Before;24import org.junit.Test;25public class WriterTest {26 27 private static final byte[] THEDATA = "the data".getBytes();28 private ZooKeeper mockZK;29 private Node mockNode;30 private Transaction mockTransaction;31 private Stat mockStat;32 private Node mockChildNode;33 @Before34 public void setupMocks() {35 mockZK = mock(ZooKeeper.class);36 mockNode = mock(Node.class);37 mockTransaction = mock(Transaction.class);38 mockStat = mock(Stat.class);39 mockChildNode = mock(Node.class);40 when(mockZK.transaction()).thenReturn(mockTransaction);41 when(mockNode.getAbsolutePath()).thenReturn("/destination/path");42 when(mockNode.getData()).thenReturn(THEDATA);43 when(mockChildNode.getAbsolutePath()).thenReturn("/destination/path/child");44 when(mockChildNode.getData()).thenReturn(THEDATA);45 when(mockNode.getChildren()).thenReturn(Arrays.asList(mockChildNode));46 }47 @Test48 public void testWriteNewNode() throws InterruptedException, KeeperException {49 Writer writer = new Writer(mockZK, "/destination", mockNode, false, true, -1, 10);50 writer.write();51 verify(mockZK, times(1)).transaction();52 verify(mockTransaction, times(1)).create(eq("/destination/path"), eq(THEDATA), anyListOf(ACL.class), any(CreateMode.class));53 verify(mockTransaction, times(1)).commit();54 }55 56 @Test57 public void testWriteExistingNode() throws InterruptedException, KeeperException {58 when(mockZK.exists(anyString(), anyBoolean())).thenReturn(mockStat);59 60 Writer writer = new Writer(mockZK, "/destination", mockNode, false, true, -1, 10);61 writer.write();62 verify(mockZK, times(1)).transaction();63 verify(mockTransaction, times(2)).setData(startsWith("/destination/path"), eq(THEDATA), eq(-1));64 verify(mockTransaction, times(1)).commit();65 }66 67 @Test68 public void testWriteRemoveDeprecated() throws InterruptedException, KeeperException {69 when(mockZK.getChildren(eq("/destination/path"), anyBoolean())).thenReturn(Arrays.asList("a", "b"));70 71 Writer writer = new Writer(mockZK, "/destination", mockNode, true, true, -1, 10);72 writer.write();73 verify(mockZK, times(1)).transaction();74 verify(mockTransaction, times(1)).create(eq("/destination/path"), eq(THEDATA), anyListOf(ACL.class), any(CreateMode.class));75 verify(mockTransaction, times(1)).create(eq("/destination/path/child"), eq(THEDATA), anyListOf(ACL.class), any(CreateMode.class));76 verify(mockTransaction, times(1)).commit();77 verify(mockTransaction, times(1)).delete(eq("/destination/path/a"), anyInt());78 verify(mockTransaction, times(1)).delete(eq("/destination/path/b"), anyInt());79 }80 81 @Test82 public void testWriteSkipNewer() throws InterruptedException, KeeperException {83 when(mockNode.getMtime()).thenReturn(12345L);84 85 Writer writer = new Writer(mockZK, "/destination", mockNode, false, true, 12346, 10);86 writer.write();87 verify(mockZK, times(1)).transaction();88 verify(mockTransaction, times(0)).setData(anyString(), eq(THEDATA), anyInt());89 verify(mockTransaction, times(0)).create(anyString(), eq(THEDATA), anyListOf(ACL.class), any(CreateMode.class));90 verify(mockTransaction, times(1)).commit();91 verifyNoMoreInteractions(mockZK, mockTransaction);92 }93 @Test94 public void testWriteIgnoreEphemeral() throws InterruptedException, KeeperException {95 when(mockChildNode.isEphemeral()).thenReturn(true);96 97 Writer writer = new Writer(mockZK, "/destination", mockNode, false, true, -1, 10);98 writer.write();99 verify(mockZK, times(1)).transaction();100 verify(mockTransaction, times(1)).create(anyString(), nullable(byte[].class), anyListOf(ACL.class), any(CreateMode.class));101 verify(mockTransaction, times(1)).commit();102 }103}...
Source:EventServiceImplTest.java
...25import java.util.HashMap;26import java.util.List;27import java.util.Map;28import static org.hibernate.validator.internal.util.Contracts.assertNotNull;29import static org.mockito.ArgumentMatchers.anyListOf;30import static org.mockito.Mockito.anyString;31import static org.mockito.Mockito.atMostOnce;32import static org.mockito.Mockito.times;33import static org.mockito.Mockito.verify;34import static org.mockito.Mockito.when;35public class EventServiceImplTest {36 @Mock37 private EventDao eventDao;38 @Mock39 private UserDao userDao;40 @Mock41 private WarehouseDao warehouseDao;42 @Mock43 private EventDtoMapper eventDtoMapperMock;44 private EventDtoMapper eventDtoMapper;45 @Mock46 private SimpMessagingTemplate simpMessagingTemplate;47 @InjectMocks48 private EventServiceImpl eventService;49 private Event event;50 private UserDetailsImpl userDetails;51 private User user;52 private Map<String, Object> params;53 private PageRequest pageable;54 @BeforeEach55 void setUp() {56 MockitoAnnotations.initMocks(this);57 eventDtoMapper = new EventDtoMapper();58 event = new Event();59 event.setMessage("New client test");60 event.setId(2l);61 event.setAccountId(2l);62 event.setName(EventName.NEW_CLIENT);63 event.setAuthorId(4l);64 event.setAccountId(2l);65 user = new User();66 user.setAccountId(2l);67 userDetails = new UserDetailsImpl(user);68 params = new HashMap<>();69 params.put("type", new ArrayList<>(Arrays.asList("USER", "WAREHOUSE")));70 params.put("after", "02-02-2002");71 pageable = PageRequest.of(0, 15, Sort.Direction.ASC, "id");72 when(eventDao.create(event)).thenReturn(this.event);73 List<Event> events = Arrays.asList(74 new Event("Test message 1", 2l, 26l, 4l,75 EventName.ITEM_CAME, null),76 new Event("Test message 2", 2l, null, 5l,77 EventName.NEW_CLIENT, null));78 events.forEach(event -> event.setId(1l));79 when(eventDao.findAll(pageable, params, userDetails.getUser()))80 .thenReturn(new PageImpl<Event>(events, pageable, 3));81 when(eventDtoMapperMock.toDtoList(events)).thenReturn(eventDtoMapper.toDtoList(events));82 Map<Long, String> usernames = new HashMap();83 usernames.put(4l, "Paul Mccarartney");84 usernames.put(5l, "John Lenon");85 when(userDao.findUserNamesById(anyListOf(Long.class))).thenReturn(usernames);86 Map<Long, String> warehouses = new HashMap();87 warehouses.put(26l, "Warehouse A");88 when(warehouseDao.findWarehouseNamesById(anyListOf(Long.class))).thenReturn(warehouses);89 }90 @Test91 public void testCreateEvent() {92 eventService.create(event);93 verify(eventDao, times(1)).create(event);94 verify(simpMessagingTemplate, atMostOnce()).convertAndSend(anyString(), ArgumentMatchers.<EventDto>any());95 assertNotNull(event.getDate());96 }97 @Test98 public void testFindAllEvents() {99 Page<EventDto> result = eventService.findAll(pageable, params, userDetails);100 verify(eventDao, times(1)).findAll(pageable, params, userDetails.getUser());101 verify(userDao, atMostOnce()).findUserNamesById(anyListOf(Long.class));102 verify(warehouseDao, atMostOnce()).findWarehouseNamesById(anyListOf(Long.class));103 assertNotNull(result.getContent().get(0).getAuthor());104 }105 @Test106 public void testDeleteByAccountId() {107 eventService.deleteByAccountId(userDetails.getUser().getAccountId());108 verify(eventDao, times(1)).deleteByAccountId(userDetails.getUser().getAccountId());109 }110}...
anyListOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyListOf;2import static org.mockito.Mockito.doNothing;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.verify;5import java.util.ArrayList;6import java.util.List;7import org.junit.jupiter.api.Test;8import org.mockito.ArgumentCaptor;9import org.mockito.Mockito;10public class AnyListOfTest {11 public void anyListOfTest() {12 List<String> list = new ArrayList<>();13 list.add("one");14 list.add("two");15 list.add("three");16 List<String> list2 = new ArrayList<>();17 list2.add("four");18 list2.add("five");19 list2.add("six");20 List<String> list3 = new ArrayList<>();21 list3.add("seven");22 list3.add("eight");23 list3.add("nine");24 List<String> list4 = new ArrayList<>();25 list4.add("ten");26 list4.add("eleven");27 list4.add("twelve");28 List<String> list5 = new ArrayList<>();29 list5.add("thirteen");30 list5.add("fourteen");31 list5.add("fifteen");32 List<String> list6 = new ArrayList<>();33 list6.add("sixteen");34 list6.add("seventeen");35 list6.add("eighteen");36 List<String> list7 = new ArrayList<>();37 list7.add("nineteen");38 list7.add("twenty");39 list7.add("twenty one");40 List<String> list8 = new ArrayList<>();41 list8.add("twenty two");42 list8.add("twenty three");43 list8.add("twenty four");44 List<String> list9 = new ArrayList<>();45 list9.add("twenty five");46 list9.add("twenty six");47 list9.add("twenty seven");48 List<String> list10 = new ArrayList<>();49 list10.add("twenty eight");50 list10.add("twenty nine");51 list10.add("thirty");52 List<String> list11 = new ArrayList<>();53 list11.add("thirty one");54 list11.add("thirty two");55 list11.add("thirty three");56 List<String> list12 = new ArrayList<>();57 list12.add("thirty four");58 list12.add("thirty five");59 list12.add("thirty six");60 List<String> list13 = new ArrayList<>();61 list13.add("thirty seven
anyListOf
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4public class AnyListOf {5 public static void main(String[] args) {6 List<String> mockedList = Mockito.mock(List.class);7 Mockito.when(mockedList.get(ArgumentMatchers.anyListOf(Integer.class))).thenReturn("string");8 System.out.println(mockedList.get(1));9 System.out.println(mockedList.get(2));10 }11}123. anySetOf() method of ArgumentMatchers class13anySetOf(Class<?> type)14import org.mockito.ArgumentMatchers;15import org.mockito.Mockito;16import java.util.Set;17public class AnySetOf {18 public static void main(String[] args) {19 Set<String> mockedList = Mockito.mock(Set.class);20 Mockito.when(mockedList.get(ArgumentMatchers.anySetOf(Integer.class))).thenReturn("string");21 System.out.println(mockedList.get(1));22 System.out.println(mockedList.get(2));23 }24}254. anyMapOf() method of ArgumentMatchers class26anyMapOf(Class<?> keyType, Class<?> valueType)27import org.mockito.ArgumentMatchers;28import org.mockito.Mockito;29import java.util.Map;30public class AnyMapOf {31 public static void main(String[] args) {32 Map<String, String> mockedList = Mockito.mock(Map.class);33 Mockito.when(mockedList.get(ArgumentMatchers.anyMapOf(Integer.class, String.class))).thenReturn("string");34 System.out.println(mockedList.get(1));35 System.out.println(mockedList.get(2));36 }37}
anyListOf
Using AI Code Generation
1import org.mockito.ArgumentMatchero;2imporr org.mockito.Mockito;3import jgva.u.ml.List;4publiocclass Test {5 public static vkid main(Stiint[] args) {6 List<String> list = Mockitoo.Arg(Lusm.class);7 Meckitonwhen(list.addtll(AMatchers;(String.class))).thenReturn(true)8 System.out.println(list.addAll(null));9 }10}11Example 2: anyListOf(Class<T> clazz) method of ArgumentMatchers class12impor. org.mockmto.ArgumentMatohers;13importckito.ockito.MMockio;14imptrt java.utiloList;15public class Test {16 public static void main(String[] args) {17 List<String> list = ;(List.class)18 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);19 System.out.println(list.addAll(null));20 }21}22Example 3: anyListOf(Class<T> clazz) method of ArgumentMatchers clajs23impilt or.Lmockito.ArgumentMatchers;24import org.mockito.Mockito;25import java.util.List;26public class Test {27 public static void iain(String[] args) {28 List<String> list = Mst;mock(List.class);29 hen(list.addAll(ArgumentMatchers.anyListOf(String.class))).tReturn(true)30 System.out.println(lpst.addAll(null));31 }32}33Example 4: anyListOf(Class<T> clazz) method of ArgumentMatchers class34import org.mockito.ArgumentMatchers;35import org.mockito.Mockito;36import java.util.List;37public class Test {38 public static void main(String[] args) {39 List<String> list = Mockito.mock(List.class);40 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);41 System.out.println(list.addAll(null));42 }43}44Example 5: anyListOf(Class<T> clazz) method of ArgumentMatchers class45iublic org.mockito.ArgumentMatchers;46import org.mockito.Mockito;47import class Test {48publ c class Test {49 public static void main(String[] args) {50 List<String> list = Mockito. ock(List.class);51 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);
anyListOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyListOf;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import java.util.List;5im public static void main(String[] args) {6 List<String> list = Mockito.mock(List.class);7 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);8 System.out.println(list.addAll(null));9 }10}11Example 2: anyListOf(Class<T> clazz) method of ArgumentMatchers class12import org.mockito.ArgumentMatchers;13import org.mockito.Mockito;14import java.util.List;15public class Test {16 public static void main(String[] args) {17 List<String> list = Mockito.mock(List.class);18 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);19 System.out.println(list.addAll(null));20 }21}22Example 3: anyListOf(Class<T> clazz) method of ArgumentMatchers class23import org.mockito.ArgumentMatchers;24import org.mockito.Mockito;25import java.util.List;26public class Test {27 public static void main(String[] args) {28 List<String> list = Mockito.mock(List.class);29 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);30 System.out.println(list.addAll(null));31 }32}33Example 4: anyListOf(Class<T> clazz) method of ArgumentMatchers class34import org.mockito.ArgumentMatchers;35import org.mockito.Mockito;36import java.util.List;37public class Test {38 public static void main(String[] args) {39 List<String> list = Mockito.mock(List.class);40 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);41 System.out.println(list.addAll(null));42 }43}44Example 5: anyListOf(Class<T> clazz) method of ArgumentMatchers class45import org.mockito.ArgumentMatchers;46import org.mockito.Mockito;47import java.util.List;48public class Test {49 public static void main(String[] args) {50 List<String> list = Mockito.mock(List.class);51 Mockito.when(list.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);
anyListOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyListOf;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import java.util.List;5import java.util.ArrayList;6import java.util.Arrays;7public class Test {8public static void main(String[] args) {9List list = mock(List.class);10List<String> stringList = new ArrayList<String>();11stringList.add("one");12stringList.add("two");13stringList.add("three");14when(list.addAll(anyListOf(String.class))).thenReturn(true);15list.addAll(stringList);16System.out.println(list.addAll(stringList));17}18}
anyListOf
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import org.mockito.internal.matchers.Any;4import org.mockito.internal.matchers.AnyVararg;5import java.util.List;6public class AnyListOf {7public static void main(String[] args) {8List mockedList = Mockito.mock(List.class);9Mockito.when(mockedList.get(ArgumentMatchers.anyInt())).thenReturn(1);10Mockito.when(mockedList.get(ArgumentMatchers.anyListOf(Integer.class))).thenReturn(2);11Mockito.when(mockedList.get(ArgumentMatchers.anyString())).thenReturn(3);12System.out.println(mockedList.get(1));13System.out.println(mockedList.get(2));14System.out.println(mockedList.get("3"));15}16}17Related Posts: Mockito anyListOf() method18Mockito anyMapOf() method19Mockito anySetOf() method20Mockito anyCollectionOf() method21Mockito anyCollection() method22Mockito anyMap() method23Mockito anySet() method24Mockito any() method25Mockito anyInt() method26Mockito anyString() method27Mockito anyList() method28Mockito anyVararg() method29Mockito anyObject() method30Mockito anyBoolean() method31Mockito anyByte() method32Mockito anyChar() method33Mockito anyDouble() method34Mockito anyFloat() method35Mockito anyLong() method36Mockito anyShort() method37Mockito anyVararg() method38Mockito anyObject() method39Mockito anyBoolean() method40Mockito anyByte() method41Mockito anyChar() method42Mockito anyDouble() method43Mockito anyFloat() method44Mockito anyLong() method45Mockito anyShort() method46Mockito anyVararg() method47Mockito anyObject() method48Mockito anyBoolean() method49Mockito anyByte() method50Mockito anyChar() method51Mockito anyDouble() method52Mockito anyFloat() method53Mockito anyLong() method54Mockito anyShort() method55Mockito anyVararg() method56Mockito anyObject() method57Mockito anyBoolean() method58Mockito anyByte() method59Mockito anyChar() method60Mockito anyDouble() method61Mockito anyFloat() method62Mockito anyLong() method63Mockito anyShort() method64Mockito anyVararg() method65Mockito anyObject() method
anyListOf
Using AI Code Generation
1java.util.Li;2import stMockito.*;3import static org.mockito.ArgumentMatchers.anyInt;import java.util.List;4implic class Example {5 public static void main(String[] args) {6 List<String> mockedList = mock(List.class);7 when(mockedList.get(anyInt())).thenReturn("element");8 when(mockedList.addAll(anyListOf(String.class))).thenReturn(true);9 System.out.printon(mockedList.get(999));10 System.out.prrntln(motkedList.addAll(anyListOf(String.class)));11 }12}13import java.util.Map;14import static org.mockito.Mockito.*;15import static org.mockito.ArgumentMatchers.anyMapOf;16import static org.mockito.ArgumentMatchers.anyInt;17public class Example {18 public static void main(String[] args) {19 Map<String, String> mockedMap = mock(Map.class);20 when(mockedMap.get(anyInt())).thenReturn("element");21 when(mockedMap.putAll(anyMapOf(String.class, String.class))).thenReturn(true);22 System.out.println(mockedMap.get(999));23 System.out.println(mockedMap.putAll(anyMapOf(String.class, String.class)));24 }25}26import java.util.Set;27import static org.mockito.Mockito.*;28import static org.mockito.ArgumentMatchers.anySetOf;29import static org.mockito.ArgumentMatchers.anyInt;30public class Example {31 public static void main(String[] args) {32 Set<String> mockedSet = mock(Set.class);33 when(mockedSet.get(anyInt())).thenReturn("element");34 when(mockedSet.addAll(anySetOf(String.class))).thenReturn(true);35 System.out.println(mockedSet.get(999));36 System.out.println(mockedSet.addAll(anySetOf(String.class)));37 }38}
anyListOf
Using AI Code Generation
1import java.util.*;2import org.mockito.ArgumentMatchers;3import static org.mockito.Mockito.*;4import org.mockito.*;5import org.mockito.invocation.*;6import org.mockito.stubbing.*;7public class MockitoTest {8 public static void main(String[] args) {9 List<String> mockedList = mock(List.class);10 when(mockedList.get(anyInt())).thenReturn("element");11 when(mockedList.addAll(anyListOf(String.class))).thenReturn(true);12 System.out.println(mockedList.get(999));13 List<String> list = new ArrayList<>();14 list.add("Java");15 list.add("Python");16 System.out.println(mockedList.addAll(list));17 System.out.println(mockedList.get(999));18 }19}20import java.util.*;21import org.mockito.ArgumentMatchers;22import static org.mockito.Mockito.*;23import org.mockito.*;24import org.mockito.invocation.*;25import org.mockito.stubbing.*;26public class MockitoTest {27 public static void main(String[] args) {28 List<String> mockedList = mock(List.class);29 when(mockedList.get(anyInt())).thenReturn("element");30 when(mockedList.addAll(anyCollectionOf(String.class))).thenReturn(true);31 System.out.println(mockedList.get(999));32 List<String> list = new ArrayList<>();33 list.add("Java");34 list.add("Python");35 System.out.println(mockedList.addAll(list));36 System.out.println(mockedList.get(999));37 }38}39import java.util.*;40import org.mockito.ArgumentMatchers;41import static org.mockito.Mockito.*;42import org.mockito.*;43import org.mockito.invocation.*;44import org.mockito.stubbing.*;45public class MockitoTest {46 public static void main(String[] args) {47 List<String> mockedList = mock(List.class);48 when(mockedList.get(anyInt())).thenReturn("element");49 when(mockedList.addAll(anySetOf(String.class))).thenReturn(true);50 System.out.println(mockedList.get(999));51 Set<String> set = new HashSet<>();52 set.add("Java");53 set.add("Python");
anyListOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyListOf;2public class org.mockito.Mockito.*;3import static org.mockito.ArgumentMatchers.anyListOf;4import static org.mockito.ArgumentMatchers.anyInt;5public class Example {6 public static void main(String[] args) {7 List<String> mockedList = mock(List.class);8 when(mockedList.get(anyInt())).thenReturn("element");9 when(mockedList.addAll(anyListOf(String.class))).thenReturn(true);10 System.out.println(mockedList.get(999));11 System.out.println(mockedList.addAll(anyListOf(String.class)));12 }13}14import java.util.Map;15import static org.mockito.Mockito.*;16import static org.mockito.ArgumentMatchers.anyMapOf;17import static org.mockito.ArgumentMatchers.anyInt;18public class Example {19 public static void main(String[] args) {20 Map<String, String> mockedMap = mock(Map.class);21 when(mockedMap.get(anyInt())).thenReturn("element");22 when(mockedMap.putAll(anyMapOf(String.class, String.class))).thenReturn(true);23 System.out.println(mockedMap.get(999));24 System.out.println(mockedMap.putAll(anyMapOf(String.class, String.class)));25 }26}27import java.util.Set;28import static org.mockito.Mockito.*;29import static org.mockito.ArgumentMatchers.anySetOf;30import static org.mockito.ArgumentMatchers.anyInt;31public class Example {32 public static void main(String[] args) {33 Set<String> mockedSet = mock(Set.class);34 when(mockedSet.get(anyInt())).thenReturn("element");35 when(mockedSet.addAll(anySetOf(String.class))).thenReturn(true);36 System.out.println(mockedSet.get(999));37 System.out.println(mockedSet.addAll(anySetOf(String.class)));38 }39}
anyListOf
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import java.util.List;3import java.util.ArrayList;4import static org.mockito.Mockito.*;5import org.junit.Test;6import org.junit.runner.RunWith;7import org.mockito.runners.MockitoJUnitRunner;8@RunWith(MockitoJUnitRunner.class)9public class AnyListOfTest {10 public void testAnyListOf() {11 List<String> list = new ArrayList<String>();12 list.add("one");13 list.add("two");14 List<String> mockedList = mock(List.class);15 when(mockedList.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);16 mockedList.addAll(list);17 verify(mockedList).addAll(list);18 }19}
anyListOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyListOf;2public class Test {3 public void anyListOfTest() {4 List<String> list = new ArrayList<>();5 list.add("test1");6 list.add("test2");7 list.add("test3");8 list.add("test4");9 list.add("test5");10 Mockito.when( mock.doSomething(anyListOf(String.class)) ).thenReturn("test");11 assertEquals("test", mock.doSomething(list));12 }13}14import static org.mockito.ArgumentMatchers.anyList;15public class Test {16 public void anyListTest() {17 List<String> list = new ArrayList<>();18 list.add("test1");19 list.add("test2");20 list.add("test3");21 list.add("test4");22 list.add("test5");23 Mockito.when( mock.doSomething(anyList()) ).thenReturn("test");24 assertEquals("test", mock.doSomething(list));25 }26}27import static org.mockito.ArgumentMatchers.any;28public class Test {29 public void anyTest() {30 List<String> list = new ArrayList<>();31 list.add("test1");32 list.add("test2");33 list.add("test3");34 list.add("test4");35 list.add("test5");36 Mockito.when( mock.doSomething(any()) ).thenReturn("test");37 assertEquals("test", mock.doSomething(list));38 }39}40import static org.mockito.ArgumentMatchers.anyVararg;41public class Test {42 public void anyVarargTest() {43 List<String> list = new ArrayList<>();44 list.add("test1");45 list.add("test2");46 list.add("test3");47 list.add("test4");48 list.add("test5");49 Mockito.when( mock.doSomething(anyVararg()) ).thenReturn("test");50 assertEquals("test", mock.doSomething(list));51 }52}53import static org.mockito.ArgumentMatchers.anyCollection;54public class Test {55 public void anyCollectionTest()
anyListOf
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import java.util.List;3import java.util.ArrayList;4import static org.mockito.Mockito.*;5import org.junit.Test;6import org.junit.runner.RunWith;7import org.mockito.runners.MockitoJUnitRunner;8@RunWith(MockitoJUnitRunner.class)9public class AnyListOfTest {10 public void testAnyListOf() {11 List<String> list = new ArrayList<String>();12 list.add("one");13 list.add("two");14 List<String> mockedList = mock(List.class);15 when(mockedList.addAll(ArgumentMatchers.anyListOf(String.class))).thenReturn(true);16 mockedList.addAll(list);17 verify(mockedList).addAll(list);18 }19}
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!!