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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #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: 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 #16
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 #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: 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 #19
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 #20
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 #21
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 #22
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 #23
Source File: ServerRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVersionGivenEndpointIsNotAvailable() throws Exception {
    GerritRestClient gerritRestClient = EasyMock.createMock(GerritRestClient.class);
    EasyMock.expect(gerritRestClient.getRequest("/config/server/version")).andThrow(new HttpStatusException(404, "Not found", ""));
    EasyMock.replay(gerritRestClient);
    ServerRestClient serverRestClient = new ServerRestClient(gerritRestClient);

    String version = serverRestClient.getVersion();

    assertEquals(version, "<2.8");
}
 
Example #24
Source File: SAMLLogoutTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUntrustedLogoutResponse() throws Exception {
    FedizContext config = getFederationConfigurator().getFedizContext("CLIENT_TRUST");

    String requestId = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");

    String status = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Element logoutResponse = createLogoutResponse(status, TEST_REQUEST_URL, false, requestId);

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getParameter("SAMLResponse")).andReturn(encodeResponse(logoutResponse)).anyTimes();
    String relayState = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
    EasyMock.expect(req.getParameter("RelayState")).andReturn(relayState);
    EasyMock.expect(req.getParameter("wa")).andReturn(null).times(2);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(LOGOUT_URL));
    EasyMock.expect(req.getRequestURI()).andReturn(LOGOUT_URI);
    EasyMock.expect(req.getContextPath()).andReturn(LOGOUT_URI);
    EasyMock.replay(req);

    LogoutHandler logoutHandler = new LogoutHandler(config);
    Assert.assertTrue(logoutHandler.canHandleRequest(req));

    HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to validate SAMLResponse.");
    EasyMock.expectLastCall();
    EasyMock.replay(resp);
    logoutHandler.handleRequest(req, resp);
}
 
Example #25
Source File: OperationResourceInfoTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static Message createMessage() {
    Message m = new MessageImpl();
    Exchange e = new ExchangeImpl();
    m.setExchange(e);
    e.setInMessage(m);
    Endpoint endpoint = EasyMock.createMock(Endpoint.class);
    EasyMock.expect(endpoint.get("org.apache.cxf.jaxrs.comparator")).andReturn(null);
    EasyMock.replay(endpoint);
    e.put(Endpoint.class, endpoint);
    return m;
}
 
Example #26
Source File: PolicyEngineTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEndpointPolicyClientSide() throws Exception {
    Method m = PolicyEngineImpl.class.getDeclaredMethod("createEndpointPolicyInfo",
        new Class[] {EndpointInfo.class, boolean.class, Assertor.class, Message.class});
    engine = EasyMock.createMockBuilder(PolicyEngineImpl.class)
        .addMockedMethod(m).createMock(control);
    engine.init();
    EndpointInfo ei = createMockEndpointInfo();
    AssertingConduit conduit = control.createMock(AssertingConduit.class);
    EndpointPolicyImpl epi = control.createMock(EndpointPolicyImpl.class);
    EasyMock.expect(engine.createEndpointPolicyInfo(ei, true, conduit, msg)).andReturn(epi);
    control.replay();
    assertSame(epi, engine.getClientEndpointPolicy(ei, conduit, msg));
    control.verify();
}
 
Example #27
Source File: JPAEntityParserTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testForNullJPAEntity() {
  JPAEntityParser resultParser = new JPAEntityParser();
  EdmStructuralType structuralType = EasyMock.createMock(EdmStructuralType.class);
  Object map;
  try {
    map = resultParser.parse2EdmPropertyValueMap(null, structuralType);
    assertNull(map);
  } catch (ODataJPARuntimeException e) {
    fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
  }
}
 
Example #28
Source File: ControllerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests addLinkDetails() method.
 */
@Test
public void testAddLinkDetails() throws Exception {
    ospfAgent = EasyMock.createMock(OspfAgent.class);
    controller.start(ospfAgent, driverService);
    ospfRouter = new OspfRouterImpl();
    controller.addLinkDetails(ospfRouter, new OspfLinkTedImpl());
    assertThat(controller, is(notNullValue()));
}
 
Example #29
Source File: TableTest.java    From fastods with GNU General Public License v3.0 5 votes vote down vote up
@Test
public final void testGetWalker() throws IOException {
    final TableRowImpl row = PowerMock.createMock(TableRowImpl.class);
    final TableCell cell = PowerMock.createMock(TableCell.class);

    PowerMock.resetAll();
    EasyMock.expect(this.tb.getRow(this.tableWithMockBuilder, this.ta, 0)).andReturn(row);
    EasyMock.expect(row.getOrCreateCell(0)).andReturn(cell);

    PowerMock.replayAll();
    this.tableWithMockBuilder.getWalker();

    PowerMock.verifyAll();
}
 
Example #30
Source File: TestWBFreeMarkerModuleDirective.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void test_execute_catch_exception()
{
	Environment envMock = PowerMock.createMock(Environment.class);
	TemplateModel[] loopVars = null;
	TemplateDirectiveBody directiveBodyMock = null;
	
	Map params = new HashMap();
	String name = "testXYZ";
	StringModel nameModel = new StringModel(name, new DefaultObjectWrapper() );
	params.put("name", nameModel);

	try
	{
		
		WPBPageModule pageModuleMock = PowerMock.createMock(WPBPageModule.class);		
		WPBPageModulesCache pageModuleCacheMock = PowerMock.createMock(WPBPageModulesCache.class);
		EasyMock.expect(pageModuleCacheMock.getByExternalKey(name)).andThrow(new WPBIOException(""));
		
		EasyMock.expect(cacheInstancesMock.getPageModuleCache()).andReturn(pageModuleCacheMock);

		EasyMock.replay(cacheInstancesMock, templateEngineMock, envMock, pageModuleMock, pageModuleCacheMock);
		
		FreeMarkerModuleDirective templateDirective = new FreeMarkerModuleDirective();
		Whitebox.setInternalState(templateDirective, "templateEngine",templateEngineMock);
		Whitebox.setInternalState(templateDirective, "cacheInstances",cacheInstancesMock);
		PowerMock.suppressMethod(FreeMarkerModuleDirective.class, "copyParams");
		templateDirective.execute(envMock, params, loopVars, directiveBodyMock);
		
		assertTrue(false);		
	} catch (Exception e)
	{
		assertTrue(e instanceof TemplateModelException);
	}
}