Java Code Examples for org.easymock.IMocksControl#createMock()

The following examples show how to use org.easymock.IMocksControl#createMock() . 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: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void transactCommitOnlyWithNoError() throws Exception {
  IMocksControl control = createStrictControl();

  final Connection c = control.createMock(Connection.class);

  c.setAutoCommit(false);
  c.commit();
  c.close();

  control.replay();

  new DatabaseProvider(() -> c, new OptionsDefault(Flavor.postgresql)).transact((db, tx) -> {
    tx.setRollbackOnError(false);
    db.get();
  });

  control.verify();
}
 
Example 2
Source File: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void transactCommitOnlyOverrideWithError2() throws Exception {
  IMocksControl control = createStrictControl();

  final Connection c = control.createMock(Connection.class);

  c.setAutoCommit(false);
  c.rollback();
  c.close();

  control.replay();

  try {
    new DatabaseProvider(() -> c, new OptionsDefault(Flavor.postgresql)).transact((db, tx) -> {
      db.get();
      tx.setRollbackOnError(false);
      tx.setRollbackOnly(true);
      throw new DatabaseException("Oops");
    });
    fail("Should have thrown an exception");
  } catch (Exception e) {
    assertEquals("Oops", e.getMessage());
  }

  control.verify();
}
 
Example 3
Source File: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void mixedParameterTypes() throws Exception {
  IMocksControl control = createStrictControl();

  Connection c = control.createMock(Connection.class);
  PreparedStatement ps = control.createMock(PreparedStatement.class);
  ResultSet rs = control.createMock(ResultSet.class);

  expect(c.prepareStatement("select a from b where c=? and d=?")).andReturn(ps);
  ps.setObject(eq(1), eq("bye"));
  ps.setNull(eq(2), eq(Types.TIMESTAMP));
  expect(ps.executeQuery()).andReturn(rs);
  expect(rs.next()).andReturn(false);
  rs.close();
  ps.close();

  control.replay();

  assertNull(new DatabaseImpl(c, options).toSelect("select a from b where c=:x and d=?")
      .argString(":x", "bye").argDate(null).queryLongOrNull());

  control.verify();
}
 
Example 4
Source File: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void transactionRollbackFail() throws Exception {
  IMocksControl control = createStrictControl();

  Connection c = control.createMock(Connection.class);

  c.rollback();
  expectLastCall().andThrow(new SQLException("Oops"));

  control.replay();

  try {
    new DatabaseImpl(c, new OptionsDefault(Flavor.postgresql) {
      @Override
      public boolean allowTransactionControl() {
        return true;
      }
    }).rollbackNow();
    fail("Should have thrown an exception");
  } catch (DatabaseException e) {
    assertEquals("Unable to rollback transaction", e.getMessage());
  }

  control.verify();
}
 
Example 5
Source File: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void missingPositionalParameter() throws Exception {
  IMocksControl control = createStrictControl();

  Connection c = control.createMock(Connection.class);

  control.replay();

  try {
    Long value = new DatabaseImpl(c, new OptionsDefault(Flavor.postgresql) {
      int errors = 0;

      @Override
      public String generateErrorCode() {
        errors++;
        return Integer.toString(errors);
      }
    }).toSelect("select a from b where c=?").queryLongOrNull();
    fail("Should have thrown an exception, but returned " + value);
  } catch (DatabaseException e) {
    assertEquals("Error executing SQL (errorCode=1)", e.getMessage());
  }

  control.verify();
}
 
Example 6
Source File: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void transactCommitOnlyWithError() throws Exception {
  IMocksControl control = createStrictControl();

  final Connection c = control.createMock(Connection.class);

  c.setAutoCommit(false);
  c.commit();
  c.close();

  control.replay();

  try {
    new DatabaseProvider(() -> c, new OptionsDefault(Flavor.postgresql)).transact((db, tx) -> {
      tx.setRollbackOnError(false);
      db.get();
      throw new Error("Oops");
    });
    fail("Should have thrown an exception");
  } catch (Exception e) {
    assertEquals("Error during transaction", e.getMessage());
  }

  control.verify();
}
 
Example 7
Source File: DatabaseTest.java    From database with Apache License 2.0 5 votes vote down vote up
@Test
public void extraPositionalParameter() throws Exception {
  IMocksControl control = createStrictControl();

  Connection c = control.createMock(Connection.class);

  control.replay();

  try {
    Long value = new DatabaseImpl(c, new OptionsDefault(Flavor.postgresql) {
      int errors = 0;

      @Override
      public boolean isDetailedExceptions() {
        return true;
      }

      @Override
      public boolean isLogParameters() {
        return true;
      }

      @Override
      public String generateErrorCode() {
        errors++;
        return Integer.toString(errors);
      }
    }).toSelect("select a from b where c=?").argString("hi").argInteger(1).queryLongOrNull();
    fail("Should have thrown an exception but returned " + value);
  } catch (DatabaseException e) {
    assertEquals("Error executing SQL (errorCode=1): (wrong # args) query: select a from b where c=?", e.getMessage());
  }

  control.verify();
}
 
Example 8
Source File: DatabaseTest.java    From database with Apache License 2.0 5 votes vote down vote up
@Test
public void missingNamedParameter() throws Exception {
  IMocksControl control = createStrictControl();

  Connection c = control.createMock(Connection.class);

  control.replay();

  try {
    Long value = new DatabaseImpl(c, new OptionsDefault(Flavor.postgresql) {
      int errors = 0;

      @Override
      public boolean isDetailedExceptions() {
        return true;
      }

      @Override
      public boolean isLogParameters() {
        return true;
      }

      @Override
      public String generateErrorCode() {
        errors++;
        return Integer.toString(errors);
      }
    }).toSelect("select a from b where c=:x").queryLongOrNull();
    fail("Should have thrown an exception but returned " + value);
  } catch (DatabaseException e) {
    assertEquals("Error executing SQL (errorCode=1): select a from b where c=:x", e.getMessage());
  }

  control.verify();
}
 
Example 9
Source File: CXFBusLifeCycleManagerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeregistration() {

    IMocksControl ctrl = EasyMock.createStrictControl();

    BusLifeCycleListener listener1 = ctrl.createMock(BusLifeCycleListener.class);
    BusLifeCycleListener listener2 = ctrl.createMock(BusLifeCycleListener.class);
    CXFBusLifeCycleManager mgr = new CXFBusLifeCycleManager();

    mgr.registerLifeCycleListener(listener2);
    mgr.registerLifeCycleListener(listener1);
    mgr.unregisterLifeCycleListener(listener2);

    ctrl.reset();
    listener1.initComplete();
    ctrl.replay();
    mgr.initComplete();
    ctrl.verify();

    ctrl.reset();
    listener1.preShutdown();
    ctrl.replay();
    mgr.preShutdown();
    ctrl.verify();

    ctrl.reset();
    listener1.postShutdown();
    ctrl.replay();
    mgr.postShutdown();
    ctrl.verify();
}
 
Example 10
Source File: PolicyRegistryImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testAll() {
    PolicyRegistryImpl reg = new PolicyRegistryImpl();
    IMocksControl control = EasyMock.createNiceControl();
    Policy policy = control.createMock(Policy.class);
    String key = "key";
    assertNull(reg.lookup(key));
    reg.register(key, policy);
    assertSame(policy, reg.lookup(key));
    reg.remove(key);
    assertNull(reg.lookup(key));
}
 
Example 11
Source File: RestClientCdiTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "rawTypes"})
public void testCreationalContextsNotReleasedOnClientCloseUsingNormalScope() throws Exception {
    IMocksControl control = EasyMock.createStrictControl();
    BeanManager mockedBeanMgr = control.createMock(BeanManager.class);
    CreationalContext<?> mockedCreationalCtx = control.createMock(CreationalContext.class);
    Bean<?> mockedBean = control.createMock(Bean.class);
    List<String> stringList = new ArrayList<>(Collections.singleton("xyz"));

    EasyMock.expect(mockedBeanMgr.getBeans(List.class))
            .andReturn(Collections.singleton(mockedBean));
    EasyMock.expect(mockedBeanMgr.createCreationalContext(mockedBean))
            .andReturn((CreationalContext) mockedCreationalCtx);
    EasyMock.expect(mockedBeanMgr.getReference(mockedBean, List.class, mockedCreationalCtx))
            .andReturn(stringList);
    EasyMock.expect(mockedBean.getScope())
            .andReturn((Class) NormalScope.class);
    EasyMock.expect(mockedBeanMgr.isNormalScope(NormalScope.class))
            .andReturn(true);
    control.replay();

    Bus bus = new ExtensionManagerBus();
    bus.setExtension(mockedBeanMgr, BeanManager.class);

    Instance<List> i = CDIUtils.getInstanceFromCDI(List.class, bus);

    i.release();

    control.verify();
}
 
Example 12
Source File: DvcsDraftRevisionTest.java    From MOE with Apache License 2.0 5 votes vote down vote up
public void testGetLocation() {
  final File mockRepoPath = new File("/mockrepo");

  IMocksControl control = EasyMock.createControl();
  LocalWorkspace mockRevClone = control.createMock(LocalWorkspace.class);
  expect(mockRevClone.getLocalTempDir()).andReturn(mockRepoPath);

  control.replay();

  DvcsDraftRevision dr = new DvcsDraftRevision(mockRevClone);
  assertEquals(mockRepoPath.getAbsolutePath(), dr.getLocation());

  control.verify();
}
 
Example 13
Source File: FileDbTest.java    From MOE with Apache License 2.0 5 votes vote down vote up
public void testWriteDbToFile() throws Exception {
  IMocksControl control = EasyMock.createControl();
  FileSystem filesystem = control.createMock(FileSystem.class);
  File dbFile = new File("/path/to/db");
  String dbText = "{\n  \"equivalences\": [],\n  \"migrations\": []\n}\n";
  DbStorage dbStorage = GSON.fromJson(dbText, DbStorage.class);
  Db db = new FileDb(dbFile.getPath(), dbStorage, new FileDb.Writer(GSON, filesystem));
  filesystem.write(dbText, dbFile);
  EasyMock.expectLastCall();
  control.replay();
  db.write();
  control.verify();
}
 
Example 14
Source File: CorbaBindingFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateBinding() throws Exception {
    IMocksControl control = EasyMock.createNiceControl();
    BindingInfo bindingInfo = control.createMock(BindingInfo.class);

    CorbaBinding binding = (CorbaBinding)factory.createBinding(bindingInfo);
    assertNotNull(binding);
    assertTrue(CorbaBinding.class.isInstance(binding));
    List<Interceptor<? extends Message>> inInterceptors = binding.getInInterceptors();
    assertNotNull(inInterceptors);
    List<Interceptor<? extends Message>> outInterceptors = binding.getOutInterceptors();
    assertNotNull(outInterceptors);
    assertEquals(2, inInterceptors.size());
    assertEquals(2, outInterceptors.size());
}
 
Example 15
Source File: ServiceInvokerInterceptorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
Endpoint createEndpoint(Invoker i) throws Exception {
    IMocksControl control = EasyMock.createNiceControl();
    Endpoint endpoint = control.createMock(Endpoint.class);

    ServiceImpl service = new ServiceImpl((ServiceInfo)null);
    service.setInvoker(i);
    service.setExecutor(new SimpleExecutor());
    EasyMock.expect(endpoint.getService()).andReturn(service).anyTimes();

    control.replay();

    return endpoint;
}
 
Example 16
Source File: DatabaseTest.java    From database with Apache License 2.0 5 votes vote down vote up
@Test
public void otherException() throws Exception {
  IMocksControl control = createStrictControl();

  Connection c = control.createMock(Connection.class);
  PreparedStatement ps = control.createMock(PreparedStatement.class);

  expect(c.prepareStatement("select a from b")).andReturn(ps);
  expect(ps.executeQuery()).andThrow(new RuntimeException("Oops"));
  ps.close();

  control.replay();

  try {
    Long value = new DatabaseImpl(c, new OptionsDefault(Flavor.postgresql) {
      int errors = 0;

      @Override
      public boolean isDetailedExceptions() {
        return true;
      }

      @Override
      public boolean isLogParameters() {
        return true;
      }

      @Override
      public String generateErrorCode() {
        errors++;
        return Integer.toString(errors);
      }
    }).toSelect("select a from b").queryLongOrNull();
    fail("Should have thrown an exception but returned " + value);
  } catch (DatabaseException e) {
    assertEquals("Error executing SQL (errorCode=1): select a from b", e.getMessage());
  }

  control.verify();
}
 
Example 17
Source File: TestBase.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    bus = BusFactory.newInstance().createBus();

    BindingFactoryManager bfm = bus.getExtension(BindingFactoryManager.class);

    IMocksControl control = createNiceControl();
    BindingFactory bf = control.createMock(BindingFactory.class);
    Binding binding = control.createMock(Binding.class);
    expect(bf.createBinding(null)).andStubReturn(binding);
    expect(binding.getInFaultInterceptors())
        .andStubReturn(new ArrayList<Interceptor<? extends Message>>());
    expect(binding.getOutFaultInterceptors())
        .andStubReturn(new ArrayList<Interceptor<? extends Message>>());

    bfm.registerBindingFactory("http://schemas.xmlsoap.org/wsdl/soap/", bf);

    String ns = "http://apache.org/hello_world_soap_http";
    WSDLServiceFactory factory = new WSDLServiceFactory(bus, getClass()
        .getResource("/org/apache/cxf/jaxb/resources/wsdl/hello_world.wsdl").toString(),
                                                        new QName(ns, "SOAPService"));

    service = factory.create();
    endpointInfo = service.getEndpointInfo(new QName(ns, "SoapPort"));
    endpoint = new EndpointImpl(bus, service, endpointInfo);
    JAXBDataBinding db = new JAXBDataBinding();
    db.setContext(JAXBContext.newInstance(new Class[] {
        GreetMe.class,
        GreetMeResponse.class
    }));
    service.setDataBinding(db);

    operation = endpointInfo.getBinding().getOperation(new QName(ns, "greetMe"));
    operation.getOperationInfo().getInput().getMessagePartByIndex(0).setTypeClass(GreetMe.class);
    operation.getOperationInfo().getOutput()
        .getMessagePartByIndex(0).setTypeClass(GreetMeResponse.class);

    message = new MessageImpl();
    Exchange exchange = new ExchangeImpl();
    message.setExchange(exchange);

    exchange.put(Service.class, service);
    exchange.put(Endpoint.class, endpoint);
    exchange.put(Binding.class, endpoint.getBinding());
}
 
Example 18
Source File: JdbcMigrationLauncherTest.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test doing migrations with a lock race from a quick cluster
 *
 * @throws Exception if there is a problem
 */
public void testDoMigrationsWithLockRace() throws Exception {
    // Setup enough for the first
    PreparedStatementResultSetHandler h = conn.getPreparedStatementResultSetHandler();
    MockResultSet rs = h.createResultSet();
    rs.addRow(new Integer[]{new Integer(0)});
    h.prepareGlobalResultSet(rs);


    MockControl mockControl = MockControl.createStrictControl(PatchInfoStore.class);
    PatchInfoStore patchStore = (PatchInfoStore) mockControl.getMock();

    // First they see if it is locked, and it is, so they spin
    patchStore.isPatchStoreLocked();
    mockControl.setReturnValue(true);

    // Second they see if it is locked again, and it isn't, so they try and fail and spin
    patchStore.isPatchStoreLocked();
    mockControl.setReturnValue(false);
    patchStore.getPatchLevel();
    mockControl.setReturnValue(0);
    patchStore.lockPatchStore();
    mockControl.setThrowable(new IllegalStateException("The table is already locked"));

    // Finally they see if it is locked again, and it isn't, and it works
    patchStore.isPatchStoreLocked();
    mockControl.setReturnValue(false);


    patchStore.getPatchLevel();
    mockControl.setReturnValue(2, MockControl.ONE_OR_MORE);
    patchStore.lockPatchStore();

    IMocksControl migrationRunnerStrategyControl = createStrictControl();
    MigrationRunnerStrategy migrationStrategyMock = migrationRunnerStrategyControl.createMock(MigrationRunnerStrategy.class);
    expect(migrationStrategyMock.shouldMigrationRun(anyInt(), eq(patchStore))).andReturn(true).anyTimes();

    patchStore.updatePatchLevel(4);
    patchStore.updatePatchLevel(5);
    patchStore.updatePatchLevel(6);
    patchStore.updatePatchLevel(7);
    patchStore.unlockPatchStore();

    mockControl.replay();
    migrationRunnerStrategyControl.replay();

    TestJdbcMigrationLauncher testLauncher = new TestJdbcMigrationLauncher(context);
    testLauncher.getMigrationProcess().setMigrationRunnerStrategy(migrationStrategyMock);
    testLauncher.setLockPollMillis(0);
    testLauncher.setLockPollRetries(4);
    testLauncher.setIgnoreMigrationSuccessfulEvents(false);
    testLauncher.setPatchStore(patchStore);
    testLauncher.setPatchPath("com.tacitknowledge.util.migration.tasks.normal");
    testLauncher.doMigrations();
    mockControl.verify();
}
 
Example 19
Source File: TestLoadBalancerDrainingValve.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void runValve(String jkActivation,
                      boolean validSessionId,
                      boolean expectInvokeNext,
                      boolean enableIgnore,
                      String queryString) throws Exception {
    IMocksControl control = EasyMock.createControl();
    ServletContext servletContext = control.createMock(ServletContext.class);
    Context ctx = control.createMock(Context.class);
    Request request = control.createMock(Request.class);
    Response response = control.createMock(Response.class);

    String sessionCookieName = "JSESSIONID";
    String sessionId = "cafebabe";
    String requestURI = "/test/path";
    SessionCookieConfig cookieConfig = new CookieConfig();
    cookieConfig.setDomain("example.com");
    cookieConfig.setName(sessionCookieName);
    cookieConfig.setPath("/");

    // Valve.init requires all of this stuff
    EasyMock.expect(ctx.getMBeanKeyProperties()).andStubReturn("");
    EasyMock.expect(ctx.getName()).andStubReturn("");
    EasyMock.expect(ctx.getPipeline()).andStubReturn(new StandardPipeline());
    EasyMock.expect(ctx.getDomain()).andStubReturn("foo");
    EasyMock.expect(ctx.getLogger()).andStubReturn(org.apache.juli.logging.LogFactory.getLog(LoadBalancerDrainingValve.class));
    EasyMock.expect(ctx.getServletContext()).andStubReturn(servletContext);

    // Set up the actual test
    EasyMock.expect(request.getAttribute(LoadBalancerDrainingValve.ATTRIBUTE_KEY_JK_LB_ACTIVATION)).andStubReturn(jkActivation);
    EasyMock.expect(Boolean.valueOf(request.isRequestedSessionIdValid())).andStubReturn(Boolean.valueOf(validSessionId));

    ArrayList<Cookie> cookies = new ArrayList<>();
    if(enableIgnore) {
        cookies.add(new Cookie("ignore", "true"));
    }

    if(!validSessionId) {
        MyCookie cookie = new MyCookie(cookieConfig.getName(), sessionId);
        cookie.setPath(cookieConfig.getPath());
        cookie.setValue(sessionId);

        cookies.add(cookie);

        EasyMock.expect(request.getRequestedSessionId()).andStubReturn(sessionId);
        EasyMock.expect(request.getRequestURI()).andStubReturn(requestURI);
        EasyMock.expect(request.getCookies()).andStubReturn(cookies.toArray(new Cookie[cookies.size()]));
        EasyMock.expect(request.getContext()).andStubReturn(ctx);
        EasyMock.expect(ctx.getSessionCookieName()).andStubReturn(sessionCookieName);
        EasyMock.expect(servletContext.getSessionCookieConfig()).andStubReturn(cookieConfig);
        EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
        EasyMock.expect(ctx.getSessionCookiePath()).andStubReturn("/");

        if (!enableIgnore) {
            EasyMock.expect(Boolean.valueOf(ctx.getSessionCookiePathUsesTrailingSlash())).andStubReturn(Boolean.TRUE);
            EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
            // Response will have cookie deleted
            MyCookie expectedCookie = new MyCookie(cookieConfig.getName(), "");
            expectedCookie.setPath(cookieConfig.getPath());
            expectedCookie.setMaxAge(0);

            // These two lines just mean EasyMock.expect(response.addCookie) but for a void method
            response.addCookie(expectedCookie);
            EasyMock.expect(ctx.getSessionCookieName()).andReturn(sessionCookieName); // Indirect call
            String expectedRequestURI = requestURI;
            if(null != queryString)
                expectedRequestURI = expectedRequestURI + '?' + queryString;
            response.setHeader("Location", expectedRequestURI);
            response.setStatus(307);
        }
    }

    Valve next = control.createMock(Valve.class);

    if(expectInvokeNext) {
        // Expect the "next" Valve to fire
        // Next 2 lines are basically EasyMock.expect(next.invoke(req,res)) but for a void method
        next.invoke(request, response);
        EasyMock.expectLastCall();
    }

    // Get set to actually test
    control.replay();

    LoadBalancerDrainingValve valve = new LoadBalancerDrainingValve();
    valve.setContainer(ctx);
    valve.init();
    valve.setNext(next);
    valve.setIgnoreCookieName("ignore");
    valve.setIgnoreCookieValue("true");

    valve.invoke(request, response);

    control.verify();
}
 
Example 20
Source File: CloudantStoreTest.java    From todo-apps with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdate() throws Exception {
  IMocksControl control = createControl();
  Response resp = control.createMock(Response.class);
  expect(resp.getStatus()).andReturn(200).times(3);
  expect(resp.getStatus()).andReturn(201);
  Capture<Class<CloudantToDo>> classToDoCapture = new Capture<Class<CloudantToDo>>();
  expect(resp.readEntity(capture(classToDoCapture))).andReturn(ctd1);
  CloudantPostResponse postResp = new CloudantPostResponse();
  postResp.setId("123");
  postResp.setOk(true);
  postResp.setRev("def");
  Capture<Class<CloudantPostResponse>> classCapture = new Capture<Class<CloudantPostResponse>>();
  expect(resp.readEntity(capture(classCapture))).andReturn(postResp);
  replay(resp);
  WebTarget wt = createMockWebTarget();
  Invocation.Builder builder = createBuilder();
  ToDo td = new ToDo();
  td.setTitle("new text");
  td.setId("123");
  expect(builder.put(isA(Entity.class))).andReturn(resp);
  expect(builder.get()).andReturn(resp).times(3);
  replay(builder);
  expect(wt.path(eq("bluemix-todo"))).andReturn(wt).times(2);
  expect(wt.path(eq("todos"))).andReturn(wt);
  expect(wt.path(eq("_design"))).andReturn(wt).times(1);
  expect(wt.queryParam(eq("rev"), eq("abc"))).andReturn(wt);
  expect(wt.path(eq("123"))).andReturn(wt).times(2);
  expect(wt.request(eq("application/json"))).andReturn(builder).anyTimes();
  replay(wt);
  CloudantStore store = new CloudantStore(wt);
  ToDo testTd = new ToDo();
  testTd.setTitle("new text");
  testTd.setId("123");
  assertEquals(testTd, store.update("123", td));
  assertEquals(CloudantPostResponse.class, classCapture.getValue());
  assertEquals(CloudantToDo.class, classToDoCapture.getValue());
  verify(resp);
  verify(wt);
  verify(builder);
}