org.easymock.EasyMock Java Examples

The following examples show how to use org.easymock.EasyMock. 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: AbstractDOMProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoPortName() throws Exception {
    EasyMock.expect(scriptMock.get("wsdlLocation", scriptMock))
        .andReturn("found");
    EasyMock.expect(scriptMock.get("serviceName", scriptMock))
        .andReturn("found");
    EasyMock.expect(scriptMock.get("portName", scriptMock))
        .andReturn(Scriptable.NOT_FOUND);
    EasyMock.replay(scriptMock);
    AbstractDOMProvider adp = new DOMMessageProvider(scriptMock, scriptMock,
                                                     null, false, false);
    try {
        adp.publish();
        fail("expected exception did not occur");
    } catch (AbstractDOMProvider.JSDOMProviderException ex) {
        assertEquals("wrong exception message",
                     AbstractDOMProvider.NO_PORT_NAME, ex.getMessage());
    }
    EasyMock.verify(scriptMock);
}
 
Example #2
Source File: RMManagerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDestination() throws NoSuchMethodException, RMException {
    Method m = RMManager.class
        .getDeclaredMethod("getReliableEndpoint", new Class[] {Message.class});
    manager = control.createMock(RMManager.class, new Method[] {m});
    Message message = control.createMock(Message.class);
    RMEndpoint rme = control.createMock(RMEndpoint.class);
    EasyMock.expect(manager.getReliableEndpoint(message)).andReturn(rme);
    Destination destination = control.createMock(Destination.class);
    EasyMock.expect(rme.getDestination()).andReturn(destination);

    control.replay();
    assertSame(destination, manager.getDestination(message));
    control.verify();

    control.reset();
    EasyMock.expect(manager.getReliableEndpoint(message)).andReturn(null);
    control.replay();
    assertNull(manager.getDestination(message));
    control.verify();
}
 
Example #3
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testGetMethod_base64Params() throws Exception {
	EasyMock.expect(mockService.testMethod("Whir?inaki")).andReturn("For?est");
	EasyMock.replay(mockService);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-get");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.addParameter("id", Integer.toString(123));
	request.addParameter("method", "testMethod");
	request.addParameter("params", net.iharder.Base64.encodeBytes("[\"Whir?inaki\"]".getBytes(StandardCharsets.UTF_8)));

	jsonRpcServer.handle(request, response);

	assertTrue("application/json-rpc".equals(response.getContentType()));
	checkSuccessfulResponse(response);
}
 
Example #4
Source File: HeaderPreAuthFederationFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomValidatorNegative() throws ServletException {
  HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
  final HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
  final FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
  EasyMock.expect(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).andReturn
      (DummyValidator.NAME);
  EasyMock.replay(request);
  EasyMock.replay(filterConfig);

  hpaff.init(filterConfig);
  List<PreAuthValidator> validators = hpaff.getValidators();
  assertEquals(validators.size(), 1);
  assertEquals(validators.get(0).getName(), DummyValidator.NAME);

  EasyMock.reset(request);
  EasyMock.expect(request.getHeader("CUSTOM_TOKEN")).andReturn("NOTHelloWorld");
  EasyMock.replay(request);
  assertFalse(PreAuthService.validate(request, filterConfig, validators));

}
 
Example #5
Source File: AmbariDynamicServiceURLCreatorTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private String getTestHdfsURL(String serviceName, String address, boolean isHttps) throws Exception {
    AmbariCluster.ServiceConfiguration hdfsSC = EasyMock.createNiceMock(AmbariCluster.ServiceConfiguration.class);
    Map<String, String> hdfsProps = new HashMap<>();
    hdfsProps.put("dfs.namenode.http-address", address);
    hdfsProps.put("dfs.namenode.https-address", address);
    hdfsProps.put("dfs.http.policy", (isHttps) ? "HTTPS_ONLY" : "HTTP_ONLY");
    EasyMock.expect(hdfsSC.getProperties()).andReturn(hdfsProps).anyTimes();
    EasyMock.replay(hdfsSC);

    AmbariCluster cluster = EasyMock.createNiceMock(AmbariCluster.class);
    EasyMock.expect(cluster.getServiceConfiguration("HDFS", "hdfs-site")).andReturn(hdfsSC).anyTimes();
    EasyMock.replay(cluster);

    // Create the URL
    List<String> urls = ServiceURLFactory.newInstance(cluster).create(serviceName, null);
    assertNotNull(urls);
    assertFalse(urls.isEmpty());
    return urls.get(0);
}
 
Example #6
Source File: MessageContextImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testContextResolver() {
    ContextResolver<JAXBContext> resolver = new CustomContextResolver();
    ProviderFactory factory = ServerProviderFactory.getInstance();
    factory.registerUserProvider(resolver);

    Message m = new MessageImpl();
    Exchange ex = new ExchangeImpl();
    m.setExchange(ex);
    ex.setInMessage(m);
    Endpoint e = EasyMock.createMock(Endpoint.class);
    EasyMock.expect(e.get(ServerProviderFactory.class.getName())).andReturn(factory);
    EasyMock.replay(e);
    ex.put(Endpoint.class, e);
    MessageContext mc = new MessageContextImpl(m);
    ContextResolver<JAXBContext> resolver2 =
        mc.getResolver(ContextResolver.class, JAXBContext.class);
    assertNotNull(resolver2);
    assertSame(resolver2, resolver);
}
 
Example #7
Source File: TableAppenderTest.java    From fastods with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void appendTwoElementsPreambleTest() throws IOException {
    PowerMock.resetAll();
    EasyMock.expect(this.tb.getName()).andReturn("table1");
    EasyMock.expect(this.tb.getStyleName()).andReturn("table-style1");
    EasyMock.expect(this.tb.getCustomValueByAttribute()).andReturn(null);
    EasyMock.expect(this.tb.getColumns())
            .andReturn(FastFullList.newList(this.newTC("x"), this.newTC("x")));
    EasyMock.expect(this.tb.getShapes()).andReturn(Collections.<Shape>emptyList());

    PowerMock.replayAll();
    this.assertPreambleXMLEquals(
            "<table:table table:name=\"table1\" table:style-name=\"table-style1\" " +
                    "table:print=\"false\">" + "<office:forms form:automatic-focus=\"false\" " +
                    "form:apply-design-mode=\"false\"/>" +
                    "<table:table-column table:style-name=\"x\" " +
                    "table:number-columns-repeated=\"2\" " +
                    "table:default-cell-style-name=\"Default\"/>" + "<table:table-column " +
                    "table:style-name=\"co1\"" + " table:number-columns-repeated=\"1022\" " +
                    "table:default-cell-style-name=\"Default\"/>");

    PowerMock.verifyAll();
}
 
Example #8
Source File: FailoverClusterInvokerTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
/**
 * @throws java.lang.Exception
 */

@Before
public void setUp() throws Exception {
    
    dic = EasyMock.createMock(Directory.class);
    
    EasyMock.expect(dic.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(dic.list(invocation)).andReturn(invokers).anyTimes();
    EasyMock.expect(dic.getInterface()).andReturn(FailoverClusterInvokerTest.class).anyTimes();
    invocation.setMethodName("method1");
    EasyMock.replay(dic);
    
    invokers.add(invoker1);
    invokers.add(invoker2);
}
 
Example #9
Source File: TableAppenderTest.java    From fastods with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void appendEmptyPreambleTest() throws IOException {
    PowerMock.resetAll();
    EasyMock.expect(this.tb.getName()).andReturn("table1");
    EasyMock.expect(this.tb.getStyleName()).andReturn("table-style1");
    EasyMock.expect(this.tb.getCustomValueByAttribute()).andReturn(null);
    EasyMock.expect(this.tb.getColumns())
            .andReturn(FastFullList.<TableColumnImpl>newListWithCapacity(1));
    EasyMock.expect(this.tb.getShapes()).andReturn(Collections.<Shape>emptyList());

    PowerMock.replayAll();
    this.assertPreambleXMLEquals(
            "<table:table table:name=\"table1\" table:style-name=\"table-style1\" " +
                    "table:print=\"false\">" + "<office:forms form:automatic-focus=\"false\" " +
                    "form:apply-design-mode=\"false\"/>" +
                    "<table:table-column table:style-name=\"co1\" " +
                    "table:number-columns-repeated=\"1024\" " +
                    "table:default-cell-style-name=\"Default\"/>");

    PowerMock.verifyAll();
}
 
Example #10
Source File: TestRemoveRequestHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveLostDevice() throws Exception {
   device.setState(Device.STATE_LOST_RECOVERABLE);
   EasyMock.expect(deviceDao.findById(device.getId())).andReturn(device);
   EasyMock.expect(service.delete(device)).andReturn(true);
   replay();

   MessageBody response = handler.handleMessage(createRemoveRequest());
   assertEquals(RemoveResponse.NAME, response.getMessageType());
   
   // NOTE device service is responsible for sending out the deleted event
   
   assertNull(platformBus.poll());
   
   verify();
}
 
Example #11
Source File: JPAProcessorImplTest.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
private GetEntitySetUriInfo getEntitySetUriInfo() {

    UriInfo objUriInfo = EasyMock.createMock(UriInfo.class);
    EasyMock.expect(objUriInfo.getStartEntitySet()).andStubReturn(getLocalEdmEntitySet());
    EasyMock.expect(objUriInfo.getTargetEntitySet()).andStubReturn(getLocalEdmEntitySet());
    EasyMock.expect(objUriInfo.getSelect()).andStubReturn(null);
    EasyMock.expect(objUriInfo.getOrderBy()).andStubReturn(getOrderByExpression());
    EasyMock.expect(objUriInfo.getTop()).andStubReturn(getTop());
    EasyMock.expect(objUriInfo.getSkip()).andStubReturn(getSkip());
    EasyMock.expect(objUriInfo.getInlineCount()).andStubReturn(getInlineCount());
    EasyMock.expect(objUriInfo.getFilter()).andStubReturn(getFilter());
    //EasyMock.expect(objUriInfo.getFunctionImport()).andStubReturn(getFunctionImport());
    EasyMock.expect(objUriInfo.getFunctionImport()).andStubReturn(null);
    EasyMock.replay(objUriInfo);
    return objUriInfo;
  }
 
Example #12
Source File: AuditServiceImplTest.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Test of audit method, of class AuditServiceImpl.
 */
public void testAudit() {
    AuditServiceImpl instance = initialiseAuditService();
    
    Audit audit = EasyMock.createMock(Audit.class);
    Audit auditReturnedByAuditMethodOfAuditServiceThread = 
            EasyMock.createMock(Audit.class);
    
    AuditServiceThread mockAuditServiceThread = EasyMock.createMock(AuditServiceThread.class);
    
    mockAuditServiceThread.run();
    EasyMock.expectLastCall();
    EasyMock.expect(mockAuditServiceThread.getAudit()).
            andReturn(auditReturnedByAuditMethodOfAuditServiceThread).anyTimes();
    EasyMock.replay(mockAuditServiceThread);
    
    EasyMock.expect(mockAuditServiceThreadFactory.create(audit)).
            andReturn(mockAuditServiceThread).anyTimes();
    EasyMock.replay(mockAuditServiceThreadFactory);
    
    assertEquals(auditReturnedByAuditMethodOfAuditServiceThread, 
            instance.audit(audit));
    
    EasyMock.verify(mockAuditServiceThread);
    EasyMock.verify(mockAuditServiceThreadFactory);
}
 
Example #13
Source File: TestPeriodicReloadingTrigger.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether the trigger can be started.
 */
@Test
public void testStart()
{
    final ScheduledFuture<Void> future = createFutureMock();
    final MutableObject<Runnable> refTask = new MutableObject<>();
    expectSchedule(null);
    EasyMock.expectLastCall().andAnswer(
            () -> {
                refTask.setValue((Runnable) EasyMock
                        .getCurrentArguments()[0]);
                return future;
            });
    EasyMock.expect(controller.checkForReloading(CTRL_PARAM)).andReturn(
            Boolean.FALSE);
    EasyMock.replay(future, controller, executor);
    final PeriodicReloadingTrigger trigger = createTrigger();
    trigger.start();
    assertTrue("Not started", trigger.isRunning());
    refTask.getValue().run();
    EasyMock.verify(future, controller, executor);
}
 
Example #14
Source File: ConcurrentUtilsTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests whether exceptions are correctly handled by initializeUnchecked().
 */
@Test
public void testInitializeUncheckedEx() throws ConcurrentException {
    @SuppressWarnings("unchecked")
    ConcurrentInitializer<Object> init = EasyMock
            .createMock(ConcurrentInitializer.class);
    final Exception cause = new Exception();
    EasyMock.expect(init.get()).andThrow(new ConcurrentException(cause));
    EasyMock.replay(init);
    try {
        ConcurrentUtils.initializeUnchecked(init);
        fail("Exception not thrown!");
    } catch (ConcurrentRuntimeException crex) {
        assertSame("Wrong cause", cause, crex.getCause());
    }
    EasyMock.verify(init);
}
 
Example #15
Source File: OspfInterfaceImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    ospfProcess = new OspfProcessImpl();
    ospfProcesses.add(ospfProcess);
    ospfInterface = new OspfInterfaceImpl();
    topologyForDeviceAndLink = new TopologyForDeviceAndLinkImpl();
    channel = EasyMock.createMock(Channel.class);
    ospfArea = createOspfArea();
    ospfInterface = createOspfInterface();
    ospfNbrHashMap = new HashMap();
    topologyForDeviceAndLink = new TopologyForDeviceAndLinkImpl();
    ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("10.10.10.10"),
                              Ip4Address.valueOf("2.2.2.2"), 2,
                              topologyForDeviceAndLink);
    ospfNbr.setNeighborId(Ip4Address.valueOf("10.10.10.10"));
    ospfNbr.setRouterPriority(0);
    ospfNbr.setNeighborDr(Ip4Address.valueOf("13.13.13.13"));
    ospfInterface.addNeighbouringRouter(ospfNbr);
    controller = new Controller();
    ospfInterfaceChannelHandler = new OspfInterfaceChannelHandler(controller, ospfProcesses);

}
 
Example #16
Source File: ContentElementTest.java    From fastods with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWrite() throws IOException {
    final ZipUTF8WriterMockHandler handler = ZipUTF8WriterMockHandler.create();
    final ZipUTF8Writer writer = handler.getInstance(ZipUTF8Writer.class);

    PowerMock.resetAll();
    this.container
            .writeFontFaceDecls(EasyMock.eq(this.xmlUtil), EasyMock.isA(Appendable.class));
    this.container
            .writeHiddenDataStyles(EasyMock.eq(this.xmlUtil), EasyMock.isA(Appendable.class));
    this.container.writeContentAutomaticStyles(EasyMock.eq(this.xmlUtil),
            EasyMock.isA(Appendable.class));

    PowerMock.replayAll();
    final Table t = this.createTable("t", 100, 100);
    this.content.addTable(t);
    this.content.write(this.xmlUtil, writer);

    DomTester.assertEquals(PREAMBLE_BODY +
                    "<office:spreadsheet>" +
                    "<table:table table:name=\"t\" table:style-name=\"ta1\" table:print=\"false\"><office:forms form:automatic-focus=\"false\" form:apply-design-mode=\"false\"/><table:table-column table:style-name=\"co1\" table:number-columns-repeated=\"1024\" table:default-cell-style-name=\"Default\"/></table:table>" +
                    "</office:spreadsheet>" +
                    POSTAMBLE_BODY,
            this.getString(handler));
}
 
Example #17
Source File: RequestHandlerImplTest.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Tests getProcessXml method.
 * @throws JMSException
 */
@Test
public void testGetProcessNames() throws JMSException {
  
  Collection<ClientRequestResult> response = new ArrayList<>();
  response.add(new ProcessNameResponse() {

    @Override
    public String getErrorMessage() {
      return null;
    }

    @Override
    public String getProcessName() {
      return "name";
    }
  });
  EasyMock.expect(jmsProxy.sendRequest(EasyMock.isA(JsonRequest.class), EasyMock.eq("c2mon.client.request"), EasyMock.eq(10000))).andReturn(response);

  EasyMock.replay(jmsProxy);

  Collection<ProcessNameResponse> xmlString = requestHandlerImpl.getProcessNames();

  EasyMock.verify(jmsProxy);
  Assert.assertEquals("name", ((ProcessNameResponse)(xmlString.iterator().next())).getProcessName());
}
 
Example #18
Source File: EdmMockUtil.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private static EdmTyped mockEdmPropertyOfSource2() {
  EdmProperty edmProperty = EasyMock.createMock(EdmProperty.class);
  EdmType type = EasyMock.createMock(EdmType.class);
  EasyMock.expect(type.getKind()).andStubReturn(EdmTypeKind.SIMPLE);
  EasyMock.replay(type);
  EdmMapping mapping = EasyMock.createMock(EdmMapping.class);
  EasyMock.expect(mapping.getInternalName()).andStubReturn("description");
  EasyMock.replay(mapping);
  try {
    EasyMock.expect(edmProperty.getName()).andStubReturn("description");
    EasyMock.expect(edmProperty.getType()).andStubReturn(type);
    EasyMock.expect(edmProperty.getMapping()).andStubReturn(mapping);
  } catch (EdmException e) {
    fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
  }
  EasyMock.replay(edmProperty);
  return edmProperty;
}
 
Example #19
Source File: HawkAccessTokenValidatorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateAccessToken() throws Exception {
    HawkAccessToken macAccessToken = new HawkAccessToken(new Client("testClientId", "testClientSecret",
                                                                      true),
                                                                      HmacAlgorithm.HmacSHA256, -1);
    HttpServletRequest httpRequest = mockHttpRequest();
    UriInfo uriInfo = mockUriInfo();

    EasyMock.expect(dataProvider.getAccessToken(macAccessToken.getTokenKey())).andReturn(macAccessToken);
    EasyMock.expect(messageContext.getHttpServletRequest()).andReturn(httpRequest);
    EasyMock.expect(messageContext.getUriInfo()).andReturn(uriInfo);
    EasyMock.replay(dataProvider, messageContext, httpRequest, uriInfo);

    String authData = getClientAuthHeader(macAccessToken);
    AccessTokenValidation tokenValidation = validator
        .validateAccessToken(messageContext,
                             OAuthConstants.HAWK_AUTHORIZATION_SCHEME,
                             authData.split(" ")[1],
                             null);
    assertNotNull(tokenValidation);
    EasyMock.verify(dataProvider, messageContext, httpRequest);
}
 
Example #20
Source File: TextCallbackTest.java    From mongodb-async-driver with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link TextCallback#exception(Throwable)}.
 */
@SuppressWarnings("unchecked")
@Test
@Deprecated
public void testException() {
    final Throwable thrown = new IllegalAccessError();

    final Callback<MongoIterator<com.allanbank.mongodb.builder.TextResult>> mockCallback = EasyMock
            .createMock(Callback.class);

    mockCallback.exception(thrown);
    expectLastCall();

    replay(mockCallback);

    final TextCallback cb = new TextCallback(mockCallback);
    cb.exception(thrown);

    verify(mockCallback);
}
 
Example #21
Source File: DataTagFacadeImplTest.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testCreateCacheObjectForSubEquipment() throws IllegalAccessException {
  Properties properties = new Properties();
  properties.put("minValue", 1);
  properties.put("maxValue", 20);
  properties.put("name", "tag_name");
  properties.put("dataType", "String");
  properties.put("mode", 0);
  properties.put("subEquipmentId", "30");
  properties.put("address", "<DataTagAddress><HardwareAddress class=\"cern.c2mon.shared.common.datatag.address.impl" +
      ".JAPCHardwareAddressImpl\"><protocol>yami</protocol><service>yami</service><device-name>TEST.CLIC" +
      ".DIAMON.1</device-name><property-name>Acquisition</property-name><data-field-name>sys.mem" +
      ".inactpct</data-field-name><column-index>-1</column-index><row-index>-1</row-index></HardwareAddress><time-to-live>3600000</time-to-live><priority>2" +
      "</priority><guaranteed-delivery>false</guaranteed-delivery></DataTagAddress>");

  dataTagCache.acquireReadLockOnKey(11L);
  dataTagCache.acquireWriteLockOnKey(11L);
  EasyMock.expect(subEquipmentFacade.getProcessIdForAbstractEquipment(30L)).andReturn(2L);
  dataTagCache.releaseReadLockOnKey(11L);
  dataTagCache.releaseWriteLockOnKey(11L);

  EasyMock.replay(subEquipmentFacade);

  DataTag tag = dataTagFacade.createCacheObject(11L, properties);
  EasyMock.verify(subEquipmentFacade);
}
 
Example #22
Source File: TestWBPageController.java    From cms with Apache License 2.0 6 votes vote down vote up
@Test
public void test_delete_noKey()
{
	try
	{
		Object key = EasyMock.expect(requestMock.getAttribute("key")).andReturn(null);
		
		String 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.delete(requestMock, responseMock, "/abc");
		EasyMock.verify(httpServletToolboxMock, requestMock, responseMock, jsonObjectConverterMock, validatorMock, adminStorageMock, objectForControllerMock);
		assertTrue (captureErrors.getValue().get("").compareTo(WPBErrors.WB_CANT_DELETE_RECORD) == 0);
		assertTrue (captureData.getValue().compareTo(returnJson) == 0);
		assertTrue (captureHttpResponse.getValue() == responseMock);	
	} catch (Exception e)
	{
		assertTrue(false);
	}
}
 
Example #23
Source File: TestAutoSaveListener.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether the file handler can be updated and is correctly
 * initialized.
 */
@Test
public void testUpdateFileHandler()
{
    final FileHandler handler = EasyMock.createMock(FileHandler.class);
    final FileHandler handler2 = EasyMock.createMock(FileHandler.class);
    handler.addFileHandlerListener(listener);
    handler.removeFileHandlerListener(listener);
    handler2.addFileHandlerListener(listener);
    EasyMock.replay(handler, handler2);
    listener.updateFileHandler(handler);
    listener.updateFileHandler(handler2);
    EasyMock.verify(handler, handler2);
}
 
Example #24
Source File: TimedSemaphoreTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepares an executor service mock to expect the start of the timer.
 *
 * @param service the mock
 * @param future the future
 */
private void prepareStartTimer(ScheduledExecutorService service,
        ScheduledFuture<?> future) {
    service.scheduleAtFixedRate((Runnable) EasyMock.anyObject(), EasyMock
            .eq(PERIOD), EasyMock.eq(PERIOD), EasyMock.eq(UNIT));
    EasyMock.expectLastCall().andReturn(future);
}
 
Example #25
Source File: CurrentTelnetHandlerTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageError() throws RemotingException {
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn(null).anyTimes();
    EasyMock.replay(mockChannel);
    String result = count.telnet(mockChannel, "test");
    assertEquals("Unsupported parameter test for pwd.", result);
}
 
Example #26
Source File: InvokerTelnetHandlerTest.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvaildMessage() throws RemotingException {
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn(null).anyTimes();
    EasyMock.replay(mockChannel);
    String result = invoke.telnet(mockChannel, "(");
    assertEquals("Invalid parameters, format: service.method(args)", result);
    EasyMock.reset(mockChannel);
}
 
Example #27
Source File: ProducerTest.java    From luxun with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testAsyncProducerPool() throws IOException {
	// 2 sync producers
	ConcurrentHashMap<Integer, AsyncProducer<String>> asyncProducers = new ConcurrentHashMap<Integer, AsyncProducer<String>>();
	AsyncProducer<String> asyncProducer1 = EasyMock.createMock(AsyncProducer.class);
	AsyncProducer<String> asyncProducer2 = EasyMock.createMock(AsyncProducer.class);
	asyncProducer1.send(topic, "test1");
	EasyMock.expectLastCall();
	asyncProducer1.close();
	EasyMock.expectLastCall();
	asyncProducer2.close();
	EasyMock.expectLastCall();
	EasyMock.replay(asyncProducer1);
	EasyMock.replay(asyncProducer2);
	
	asyncProducers.put(brokerId1, asyncProducer1);
	asyncProducers.put(brokerId2, asyncProducer2);
	
    // change producer.type to "async"
	Properties props = new Properties();
	props.put("serializer.class", StringEncoder.class.getName());
	props.put("broker.list", brokerList);
    props.put("producer.type", "async");
	ProducerPool<String> producerPool = new ProducerPool<String>(new ProducerConfig(props), new StringEncoder(), new ConcurrentHashMap<Integer, SyncProducer>(), asyncProducers , null, null);
	List<String> data = new ArrayList<String>();
	data.add("test1");
	producerPool.send(producerPool.buildProducerPoolData(topic, new Broker(0, "local", "127.0.0.1", 9092), data));
	producerPool.close();
	
	EasyMock.verify(asyncProducer1);
	EasyMock.verify(asyncProducer2);
}
 
Example #28
Source File: MAPCodecTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void setUpDecode(SoapMessage message, List<Header> headers, AddressingProperties maps,
                         String mapProperty, boolean requestor) throws Exception {
    Unmarshaller unmarshaller = control.createMock(Unmarshaller.class);
    ContextJAXBUtils.getJAXBContext().createUnmarshaller();
    EasyMock.expectLastCall().andReturn(unmarshaller);
    String uri = maps.getNamespaceURI();
    boolean exposedAsNative = Names.WSA_NAMESPACE_NAME.equals(uri);
    boolean exposedAs200408 = Names200408.WSA_NAMESPACE_NAME.equals(uri);
    boolean exposedAs200403 = Names200403.WSA_NAMESPACE_NAME.equals(uri);
    assertTrue("unexpected namescape URI: " + uri, exposedAsNative || exposedAs200408 || exposedAs200403);
    setUpHeaderDecode(headers, uri, Names.WSA_ACTION_NAME, exposedAsNative
        ? AttributedURIType.class : exposedAs200408 ? AttributedURI.class : exposedAs200403
            ? org.apache.cxf.ws.addressing.v200403.AttributedURI.class : null, 0, unmarshaller);
    setUpHeaderDecode(headers, uri, Names.WSA_MESSAGEID_NAME, exposedAsNative
        ? AttributedURIType.class : exposedAs200408 ? AttributedURI.class : exposedAs200403
            ? org.apache.cxf.ws.addressing.v200403.AttributedURI.class : null, 1, unmarshaller);
    setUpHeaderDecode(headers, uri, Names.WSA_TO_NAME, exposedAsNative
        ? AttributedURIType.class : exposedAs200408 ? AttributedURI.class : exposedAs200403
            ? org.apache.cxf.ws.addressing.v200403.AttributedURI.class : null, 2, unmarshaller);
    setUpHeaderDecode(headers, uri, Names.WSA_REPLYTO_NAME, exposedAsNative
        ? EndpointReferenceType.class : exposedAs200408
            ? Names200408.EPR_TYPE : exposedAs200403
                ? Names200403.EPR_TYPE : null, 3, unmarshaller);
    setUpHeaderDecode(headers, uri, Names.WSA_RELATESTO_NAME, exposedAsNative
        ? RelatesToType.class : exposedAs200408 ? Relationship.class : exposedAs200403
            ? org.apache.cxf.ws.addressing.v200403.Relationship.class : null, 4, unmarshaller);
    setUpHeaderDecode(headers, uri, Names.WSA_FAULTTO_NAME, exposedAsNative
        ? EndpointReferenceType.class : exposedAs200408
            ? Names200408.EPR_TYPE : exposedAs200403
                ? Names200403.EPR_TYPE : null, 5, unmarshaller);
    setUpHeaderDecode(headers, uri, Names.WSA_FROM_NAME, exposedAsNative
        ? EndpointReferenceType.class : exposedAs200408
            ? Names200408.EPR_TYPE : exposedAs200403
                ? Names200403.EPR_TYPE : null, 6, unmarshaller);
}
 
Example #29
Source File: TestRequestEmailVerificationRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private Capture<Person> mockSetup(Person curPerson, boolean personExist, boolean principalMatch, String source, int times) {
	EasyMock.expect(client.getPrincipalId()).andReturn(curPerson.getId()).times(times);
   EasyMock.expect(request.content()).andReturn(Unpooled.copiedBuffer(generateClientMessage(curPerson.getId(), generateRequest(source)).getBytes())).times(times);
   EasyMock.expect(ctx.channel()).andReturn(channel).times(times);

   EasyMock.expect(clientFactory.get(channel)).andReturn(client).times(times);
   platformMsgCapture = EasyMock.newCapture(CaptureType.ALL);     
   EasyMock.expect(platformBus.send(EasyMock.capture(platformMsgCapture))).andAnswer(
      () -> {
         return Futures.immediateFuture(null);
      }
   ).anyTimes();
   
   
   //logout always needs to be called
   client.logout();
	EasyMock.expectLastCall().times(times);   	  	
	EasyMock.expect(authenticator.expireCookie()).andReturn(new DefaultCookie("test", "test")).times(times);
	
	if(principalMatch) {
		EasyMock.expect(client.getPrincipalName()).andReturn(curPerson.getEmail()).times(times);   	
	}else{
		EasyMock.expect(client.getPrincipalName()).andReturn("[email protected]").times(times); 
	}
	if(personExist) {
		EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(curPerson).times(times);
	}else{
		EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(null).times(times);
	}
	Capture<Person> personUpdatedCapture = EasyMock.newCapture(CaptureType.ALL);
	EasyMock.expect(personDao.update(EasyMock.capture(personUpdatedCapture))).andReturn(curPerson).times(times);
	
	EasyMock.expect(mockPersonPlaceAssocDAO.findPlaceIdsByPerson(curPerson.getId())).andReturn(ImmutableSet.<UUID>of(curPerson.getCurrPlace())).anyTimes();
	
	return personUpdatedCapture;
}
 
Example #30
Source File: TestSSLValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testSslClientCertShorter() throws Exception {
    mockRequest.setHeader(valve.getSslClientCertHeader(), "shorter than hell");

    TesterLogValidationFilter f = TesterLogValidationFilter.add(null, "", null,
            "org.apache.catalina.valves.SSLValve");

    valve.invoke(mockRequest, null);

    EasyMock.verify(mockNext);
    Assert.assertNull(mockRequest.getAttribute(Globals.CERTIFICATES_ATTR));
    Assert.assertEquals(0, f.getMessageCount());
}