Java Code Examples for org.easymock.EasyMock#verify()

The following examples show how to use org.easymock.EasyMock#verify() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HeartbeatManagerImplTest.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Tests the heartbeat is sent at every tick.
 * @throws InterruptedException if sleep is interrupted
 */
@Test
public void testHeartbeat() throws InterruptedException {
  CountDownLatch latch = new CountDownLatch(2);
  mockJmsSender.send(EasyMock.isA(String.class));
  EasyMock.expectLastCall().andAnswer(() -> { latch.countDown(); return null; });
  mockJmsSender.send(EasyMock.isA(String.class));
  EasyMock.expectLastCall().andAnswer(() -> { latch.countDown(); return null; });
  EasyMock.replay(mockJmsSender);

  //start heartbeat
  heartbeatManagerImpl.setHeartbeatInterval(1);
  heartbeatManagerImpl.start();
  //wait long enough to get 2 notifications!
  latch.await();
  EasyMock.verify(mockJmsSender);
}
 
Example 2
Source File: TimedSemaphoreTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests the shutdown() method for a shared executor after the task was
 * started. In this case the task must be canceled.
 */
@Test
public void testShutdownSharedExecutorTask() throws InterruptedException {
    ScheduledExecutorService service = EasyMock
            .createMock(ScheduledExecutorService.class);
    ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
    prepareStartTimer(service, future);
    EasyMock.expect(Boolean.valueOf(future.cancel(false))).andReturn(Boolean.TRUE);
    EasyMock.replay(service, future);
    TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
            PERIOD, UNIT, LIMIT);
    semaphore.acquire();
    semaphore.shutdown();
    assertTrue("Not shutdown", semaphore.isShutdown());
    EasyMock.verify(service, future);
}
 
Example 3
Source File: TestReloadingFileBasedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether the controller's reloading state is reset when a new result
 * configuration is created.
 */
@Test
public void testResetReloadingStateInGetConfiguration()
        throws ConfigurationException
{
    final ReloadingDetector detector =
            EasyMock.createMock(ReloadingDetector.class);
    EasyMock.expect(detector.isReloadingRequired()).andReturn(Boolean.TRUE);
    detector.reloadingPerformed();
    EasyMock.replay(detector);
    final ReloadingFileBasedConfigurationBuilderTestImpl builder =
            new ReloadingFileBasedConfigurationBuilderTestImpl(detector);
    final PropertiesConfiguration config1 = builder.getConfiguration();
    builder.getReloadingController().checkForReloading(null);
    final PropertiesConfiguration config2 = builder.getConfiguration();
    assertNotSame("No new configuration instance", config1, config2);
    assertFalse("Still in reloading state", builder
            .getReloadingController().isInReloadingState());
    EasyMock.verify(detector);
}
 
Example 4
Source File: ConfigureSubEquipmentTest.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void createSubEquipmentWithNonExistentProcess() {
  // Setup Exception
  tagException.expect(ConfigurationParseException.class);

  SubEquipment subEquipment = SubEquipment.create("myEquipment").id(10L).build();
  subEquipment.setEquipmentId(1L);

  List<SubEquipment> subEquipmentList = Arrays.asList(subEquipment);

  Configuration config = new Configuration(1L);
  config.setEntities(subEquipmentList);

  // setUp Mocks:

  EasyMock.expect(equipmentCache.hasKey(1L)).andReturn(false);

  // run test
  EasyMock.replay(equipmentCache);
  parser.parse(config);
  EasyMock.verify(equipmentCache);
}
 
Example 5
Source File: DraftsApiRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGettingDraftById() throws Exception {
    String draftId = "89233d9c_56013406";
    String revisionId = "ec047590bc7fb8db7ae03ebac336488bfc1c5e12";
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("id", draftId);
    GerritRestClient gerritRestClient = new GerritRestClientBuilder()
        .expectGet("/changes/myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940/revisions/"
            + revisionId + "/drafts/" + draftId, jsonObject)
        .get();

    ChangeApiRestClient changeApiRestClient = new ChangeApiRestClient(gerritRestClient, null, null, commentsParser, null,
        null, null, null, null, null, null,
        null, null, null, null, null,
        "myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940");
    RevisionApiRestClient revisionApiRestClient = new RevisionApiRestClient(gerritRestClient, changeApiRestClient, commentsParser, null, null, null, null, revisionId);

    CommentInfo commentInfo = revisionApiRestClient.draft(draftId).get();

    Truth.assertThat(commentInfo.id).isEqualTo(draftId);
    EasyMock.verify(gerritRestClient);
}
 
Example 6
Source File: LogUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogNoParamsWithThrowable() {
    Logger log = LogUtils.getL7dLogger(LogUtilsTest.class, null, "testLogNoParamsWithThrowable");
    Handler handler = EasyMock.createNiceMock(Handler.class);
    Exception ex = new Exception("x");
    LogRecord record = new LogRecord(Level.SEVERE, "subbed in {0} only");
    record.setThrown(ex);
    EasyMock.reportMatcher(new LogRecordMatcher(record));
    handler.publish(record);
    EasyMock.replay(handler);
    synchronized (log) {
        log.addHandler(handler);
        // handler called *after* localization of message
        LogUtils.log(log, Level.SEVERE, "SUB1_MSG", ex);
        EasyMock.verify(handler);
        log.removeHandler(handler);
    }
}
 
Example 7
Source File: TimedSemaphoreTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests the methods for statistics.
 */
@Test
public void testGetAverageCallsPerPeriod() throws InterruptedException {
    final ScheduledExecutorService service = EasyMock
            .createMock(ScheduledExecutorService.class);
    final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
    prepareStartTimer(service, future);
    EasyMock.replay(service, future);
    final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
            LIMIT);
    semaphore.acquire();
    semaphore.endOfPeriod();
    assertEquals("Wrong average (1)", 1.0, semaphore
            .getAverageCallsPerPeriod(), .005);
    semaphore.acquire();
    semaphore.acquire();
    semaphore.endOfPeriod();
    assertEquals("Wrong average (2)", 1.5, semaphore
            .getAverageCallsPerPeriod(), .005);
    EasyMock.verify(service, future);
}
 
Example 8
Source File: ConfigureProcessTest.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void updateProcessWithAllFields() {
  // setup Configuration:
  Properties expectedProps = new Properties();
  Process process = buildUpdateProcessWithAllFields(1L, expectedProps);

  List<Process> processUpdateList = Arrays.asList(process);

  Configuration config = new Configuration(1L);
  config.setEntities(processUpdateList);

  // setUp Mocks:
  EasyMock.expect(processCache.hasKey(1L)).andReturn(true);

  EasyMock.replay(processCache);

  List<ConfigurationElement> parsed = parser.parse(config);

  assertEquals((long) parsed.get(0).getEntityId(), 1L);
  assertEquals(parsed.get(0).getEntity(), ConfigConstants.Entity.PROCESS);
  assertEquals(parsed.get(0).getAction(), ConfigConstants.Action.UPDATE);
  assertEquals(parsed.get(0).getElementProperties(), expectedProps);

  EasyMock.verify(processCache);
}
 
Example 9
Source File: GroupsRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testId() throws Exception {
    GerritRestClient gerritRestClient = new GerritRestClientBuilder()
        .expectGet("/groups/jdoe", MOCK_JSON_ELEMENT)
        .get();
    GroupsParser groupsParser = new GroupsParserBuilder()
        .expectParseGroupInfo(MOCK_JSON_ELEMENT, MOCK_GROUP_INFO)
        .get();
    GroupsRestClient groupsRestClient = new GroupsRestClient(gerritRestClient, groupsParser);
    groupsRestClient.id("jdoe").get();

    EasyMock.verify(gerritRestClient, groupsParser);
}
 
Example 10
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
public void incrStringIntLong() throws TimeoutException, InterruptedException, MemcachedException, CacheException {
    EasyMock.expect(client.incr("key1", 1, 10L)).andReturn(2L);
    EasyMock.replay(client);
    assertEquals(2L, clientWrapper.incr("key1", 1, 10));
    EasyMock.verify(client);
}
 
Example 11
Source File: TestWBParameterValidator.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void test_validateUpdate_null()
{
	EasyMock.expect(wbParameter.getName()).andReturn(null);
	EasyMock.replay(wbParameter);
	Map<String,String> errors = parameterValidator.validateUpdate(wbParameter);
	EasyMock.verify(wbParameter);
	assertTrue (errors.get("name").compareTo(WPBErrors.WBPARAMETER_EMPTY_NAME) == 0);
}
 
Example 12
Source File: AuditCommandFactoryImplTest.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Test of create method, of class AuditCommandFactoryImpl.
 */
public void testCreate_3args_1() {
    System.out.println("create PageAuditCommand with crawler");
    
    String url = "";
    Set<Parameter> paramSet = null;
    boolean isSite = false;
    auditCommandFactory.setAuditPageWithCrawler(true);
    AuditCommand result = this.auditCommandFactory.create(url, paramSet, isSite);
    
    assertTrue(result instanceof PageAuditCrawlerCommandImpl);
    EasyMock.verify(mockAuditDataService);
    EasyMock.verify(mockAudit);
}
 
Example 13
Source File: TestReloadingController.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that the reloading state can be reset.
 */
@Test
public void testResetReloadingState()
{
    EasyMock.expect(detector.isReloadingRequired()).andReturn(Boolean.TRUE);
    detector.reloadingPerformed();
    EasyMock.replay(detector);
    final ReloadingController ctrl = createController();
    ctrl.checkForReloading(null);
    ctrl.resetReloadingState();
    assertFalse("In reloading state", ctrl.isInReloadingState());
    EasyMock.verify(detector);
}
 
Example 14
Source File: ServerClientTest.java    From jsonrpc4j with MIT License 5 votes vote down vote up
@Test
public void testInterceptorDoingNothingCalled() throws Throwable {
	EasyMock.expect(mockService.hello()).andReturn(param1);
	RequestInterceptor interceptorMock = EasyMock.mock(RequestInterceptor.class);
	interceptorMock.interceptRequest(EasyMock.anyObject(JsonNode.class));
	EasyMock.expectLastCall().andVoid();
	server.setRequestInterceptor(interceptorMock);
	EasyMock.replay(interceptorMock, mockService);
	assertEquals(param1, client.hello());
	EasyMock.verify(interceptorMock, mockService);
}
 
Example 15
Source File: AuditServiceThreadQueueImplTest.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Test of addSiteAudit method, of class AuditServiceThreadQueueImpl.
 */
public void testAddSiteAudit() {
    System.out.println("addSiteAudit");
    
    AuditServiceThreadQueueImpl instance = new AuditServiceThreadQueueImpl();
    
    AuditCommand auditCommand = EasyMock.createMock(AuditCommand.class);
    
    // Create the mock instance
    AuditServiceThread auditServiceThread = createMockAuditServiceThread(instance);
    
    // Create the mock instance
    AuditServiceThreadFactory auditServiceThreadFactory = 
            createMockAuditServiceThreadFactory(auditCommand, auditServiceThread);
    
    instance.setAuditServiceThreadFactory(auditServiceThreadFactory);
    instance.addSiteAudit(auditCommand);
    
    // sleep to make sure the auditServiceThread is started and thus avoid
    // an unexpected error
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        Logger.getLogger(AuditServiceThreadQueueImplTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    // Verify behavior.
    EasyMock.verify(auditServiceThread);
    EasyMock.verify(auditServiceThreadFactory);
}
 
Example 16
Source File: TestWBPageModuleController.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void test_update_ok()
{
	try
	{
		String json = "{}";
		Object key = EasyMock.expect(requestMock.getAttribute("key")).andReturn("123");
		EasyMock.expect(httpServletToolboxMock.getBodyText(requestMock)).andReturn(json);
		EasyMock.expect(jsonObjectConverterMock.objectFromJSONString(json, WPBPageModule.class)).andReturn(objectForControllerMock);
		EasyMock.expect(validatorMock.validateUpdate(objectForControllerMock)).andReturn(errors);
		Capture<String> captureKey = new Capture<String>();
		Capture<Date> captureDate = new Capture<Date>();
		objectForControllerMock.setExternalKey(EasyMock.capture(captureKey));
		objectForControllerMock.setLastModified(EasyMock.capture(captureDate));
		WPBPageModule newPageModule = new WPBPageModule();
		newPageModule.setExternalKey("123");
		EasyMock.expect(adminStorageMock.update(objectForControllerMock)).andReturn(newPageModule);
		
		String returnJson = "{}"; //really doesn't matter
		EasyMock.expect(jsonObjectConverterMock.JSONStringFromObject(newPageModule, null)).andReturn(returnJson);
		Capture<HttpServletResponse> captureHttpResponse = new Capture<HttpServletResponse>();
		Capture<String> captureData = new Capture<String>();
		Capture<Map<String, String>> captureErrors = new Capture<Map<String,String>>();
		httpServletToolboxMock.writeBodyResponseAsJson(EasyMock.capture(captureHttpResponse), 
												   EasyMock.capture(captureData), 
												   EasyMock.capture(captureErrors));
		EasyMock.replay(httpServletToolboxMock, requestMock, responseMock, jsonObjectConverterMock, validatorMock, adminStorageMock, objectForControllerMock);
		controllerForTest.update(requestMock, responseMock, "/abc");
		EasyMock.verify(httpServletToolboxMock, requestMock, responseMock, jsonObjectConverterMock, validatorMock, adminStorageMock, objectForControllerMock);
		
		assertTrue (captureErrors.getValue() == errors);
		assertTrue (captureData.getValue().compareTo(returnJson) == 0);
		assertTrue (captureHttpResponse.getValue() == responseMock);
		assertTrue (captureKey.getValue().compareTo("123") == 0);
		assertTrue (captureDate.getValue() != null);
	} catch (Exception e)
	{
		assertTrue(false);
	}
}
 
Example 17
Source File: ProjectNodeTest.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateProjectionWithFieldNameExpressionPairs() {
  mockSourceNode();
  final BooleanLiteral trueExpression = new BooleanLiteral("true");
  final BooleanLiteral falseExpression = new BooleanLiteral("false");
  EasyMock.expect(stream.select(
      Arrays.asList(new Pair<>("field1", trueExpression),
          new Pair<>("field2", falseExpression))))
      .andReturn(stream);

  EasyMock.replay(source, stream);

  final ProjectNode node = new ProjectNode(new PlanNodeId("1"),
      source,
      SchemaBuilder.struct()
          .field("field1", Schema.STRING_SCHEMA)
          .field("field2", Schema.STRING_SCHEMA)
          .build(),
      Arrays.asList(trueExpression, falseExpression));

  node.buildStream(builder,
      ksqlConfig,
      kafkaTopicClient,
      functionRegistry,
      props, new MockSchemaRegistryClient());

  EasyMock.verify(stream);
}
 
Example 18
Source File: TestAlarmSubsystemSecurity.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
protected void verify() {
	EasyMock.verify(incidentService);
}
 
Example 19
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testExitCodeAndFallback()
    throws ExecutionException, InterruptedException, IOException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(2);
  EasyMock.replay(eventBus);
  String mockWorker = "mock_worker";
  RemoteExecutionMetadata remoteExecutionMetadata =
      RemoteExecutionMetadata.newBuilder()
          .setWorkerInfo(WorkerInfo.newBuilder().setHostname(mockWorker).build())
          .setExecutedActionInfo(
              ExecutedActionInfo.newBuilder()
                  .setIsFallbackEnabledForCompletedAction(
                      BoolValue.newBuilder().setValue(true).build())
                  .build())
          .build();

  StepFailedException exc =
      StepFailedException.createForFailingStepWithExitCode(
          new AbstractExecutionStep("remote_execution") {
            @Override
            public StepExecutionResult execute(ExecutionContext context) {
              throw new RuntimeException();
            }
          },
          executionContext,
          StepExecutionResult.builder().setExitCode(1).setStderr("").build(),
          remoteExecutionMetadata);

  // Just here to test if this is serializable by jackson, as we do Log.warn this.
  new ObjectMapper().writeValueAsString(exc);

  EasyMock.expect(strategyBuildResult.getBuildResult())
      .andReturn(Futures.immediateFailedFuture(exc))
      .times(2);
  BuildResult localResult = successBuildResult("//local/did:though");
  EasyMock.expect(buildStrategyContext.runWithDefaultBehavior())
      .andReturn(Futures.immediateFuture(Optional.of(localResult)))
      .once();
  EasyMock.expect(buildStrategyContext.getExecutorService()).andReturn(directExecutor).once();
  EasyMock.expect(strategyBuildResult.getRuleContext()).andReturn(ruleContext);

  EasyMock.replay(strategyBuildResult, buildStrategyContext);
  FallbackStrategyBuildResult fallbackStrategyBuildResult =
      new FallbackStrategyBuildResult(
          RULE_NAME, strategyBuildResult, buildStrategyContext, eventBus, true, false, false);
  Assert.assertEquals(
      localResult.getStatus(),
      fallbackStrategyBuildResult.getBuildResult().get().get().getStatus());
  EasyMock.verify(strategyBuildResult, buildStrategyContext);

  List<LocalFallbackEvent> events = eventCapture.getValues();
  Assert.assertTrue(events.get(0) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(1) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(1);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.OK);
  Assert.assertEquals(finishedEvent.getExitCode(), OptionalInt.of(1));
  Assert.assertEquals(
      finishedEvent.getRemoteExecutionMetadata().get().getWorkerInfo().getHostname(), mockWorker);
}
 
Example 20
Source File: GroupsRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 4 votes vote down vote up
public void verify() {
    EasyMock.verify(gerritRestClient, groupsParser);
}