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 Project: cxf   Author: apache   File: AbstractDOMProviderTest.java    License: 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 Project: cxf   Author: apache   File: RMManagerTest.java    License: 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 Project: jsonrpc4j   Author: briandilley   File: JsonRpcServerTest.java    License: 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 Project: knox   Author: apache   File: HeaderPreAuthFederationFilterTest.java    License: 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 Project: knox   Author: apache   File: AmbariDynamicServiceURLCreatorTest.java    License: 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 Project: cxf   Author: apache   File: MessageContextImplTest.java    License: 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 Project: fastods   Author: jferard   File: TableAppenderTest.java    License: 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 Project: dubbox   Author: hutai123   File: FailoverClusterInvokerTest.java    License: 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 Project: fastods   Author: jferard   File: TableAppenderTest.java    License: 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 Project: arcusplatform   Author: arcus-smart-home   File: TestRemoveRequestHandler.java    License: 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 Project: cloud-odata-java   Author: SAP   File: JPAProcessorImplTest.java    License: 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 Project: Asqatasun   Author: Asqatasun   File: AuditServiceImplTest.java    License: 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 Project: commons-configuration   Author: apache   File: TestPeriodicReloadingTrigger.java    License: 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 Project: astor   Author: SpoonLabs   File: ConcurrentUtilsTest.java    License: 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 Project: onos   Author: opennetworkinglab   File: OspfInterfaceImplTest.java    License: 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 Project: fastods   Author: jferard   File: ContentElementTest.java    License: 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 Project: c2mon   Author: c2mon   File: RequestHandlerImplTest.java    License: 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 Project: olingo-odata2   Author: apache   File: EdmMockUtil.java    License: 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 Project: cxf   Author: apache   File: HawkAccessTokenValidatorTest.java    License: 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 Project: mongodb-async-driver   Author: allanbank   File: TextCallbackTest.java    License: 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 Project: c2mon   Author: c2mon   File: DataTagFacadeImplTest.java    License: 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 Project: cms   Author: webpagebytes   File: TestWBPageController.java    License: 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 Project: commons-configuration   Author: apache   File: TestAutoSaveListener.java    License: 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 Project: astor   Author: SpoonLabs   File: TimedSemaphoreTest.java    License: 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 Project: dubbox   Author: remoting   File: CurrentTelnetHandlerTest.java    License: 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 Project: dubbo3   Author: linux-china   File: InvokerTelnetHandlerTest.java    License: 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 Project: luxun   Author: bulldog2011   File: ProducerTest.java    License: 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 Project: cxf   Author: apache   File: MAPCodecTest.java    License: 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 Project: arcusplatform   Author: arcus-smart-home   File: TestRequestEmailVerificationRESTHandler.java    License: 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 Project: Tomcat8-Source-Read   Author: chenmudu   File: TestSSLValve.java    License: 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());
}