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

The following examples show how to use org.easymock.IMocksControl#verify() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void mixedParameterTypesReversed() 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();

  // Reverse order of args should be the same
  assertNull(new DatabaseImpl(c, options).toSelect("select a from b where c=:x and d=?")
      .argDate(null).argString(":x", "bye").queryLongOrNull());

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

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

  control.replay();

  try {
    Long value = new DatabaseImpl(c, options).toSelect("select a from b where c=:x")
        .argString("x", "hi").argString("y", "bye").queryLongOrNull();
    fail("Should have thrown an exception but returned " + value);
  } catch (DatabaseException e) {
    assertEquals("Error executing SQL (errorCode=1)", 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 transactRollbackOnErrorWithError() 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 -> {
      db.get();
      throw new Exception("Oops");
    });
    fail("Should have thrown an exception");
  } catch (Exception e) {
    assertEquals("Error during transaction", e.getMessage());
  }

  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 transactRollbackOnErrorWithNoError() 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) -> {
    db.get();
  });

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

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

  c.commit();

  control.replay();

  new DatabaseImpl(c, new OptionsDefault(Flavor.postgresql) {
    @Override
    public boolean allowTransactionControl() {
      return true;
    }
  }).commitNow();

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

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

  expect(c.prepareStatement("insert into x (y) values (1)")).andReturn(ps);
  expect(ps.executeUpdate()).andReturn(2);
  ps.close();

  control.replay();

  try {
    new DatabaseImpl(c, options).toInsert("insert into x (y) values (1)").insert(1);
    fail("Should have thrown an exception");
  } catch (DatabaseException e) {
    assertThat(e.getMessage(), containsString("The number of affected rows was 2, but 1 were expected."));
  }

  control.verify();
}
 
Example 8
Source File: DatabaseTest.java    From database with Apache License 2.0 6 votes vote down vote up
@Test
public void sqlArgLongNull() 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=?")).andReturn(ps);
  ps.setNull(eq(1), eq(Types.NUMERIC));
  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=?").argLong(null).queryLongOrNull());

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

    IMocksControl ctrl = EasyMock.createStrictControl();

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

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

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

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

    ctrl.reset();
    listener2.postShutdown();
    listener1.postShutdown();
    ctrl.replay();
    mgr.postShutdown();
    ctrl.verify();
}
 
Example 10
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 11
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 12
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 13
Source File: PolicyDataEngineImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Simply check that it runs without any exceptions
 *
 * @param assertionInfoMap
 */
private void checkAssertWithMap(AssertionInfoMap assertionInfoMap) {
    PolicyDataEngineImpl pde = new PolicyDataEngineImpl(null);
    pde.setPolicyEngine(new PolicyEngineImpl());
    TestPolicy confPol = new TestPolicy();
    IMocksControl control = EasyMock.createControl();
    PolicyCalculator<TestPolicy> policyCalculator = new TestPolicyCalculator();
    Message message = control.createMock(Message.class);
    EasyMock.expect(message.get(TestPolicy.class)).andReturn(confPol);
    EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(assertionInfoMap);
    control.replay();
    pde.assertMessage(message, confPol, policyCalculator);
    control.verify();
}
 
Example 14
Source File: Wsdl11AttachmentPolicyProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void oneTimeSetUp() throws Exception {

    IMocksControl control = EasyMock.createNiceControl();
    Bus bus = control.createMock(Bus.class);
    WSDLManager manager = new WSDLManagerImpl();
    WSDLServiceBuilder builder = new WSDLServiceBuilder(bus);
    DestinationFactoryManager dfm = control.createMock(DestinationFactoryManager.class);
    EasyMock.expect(bus.getExtension(DestinationFactoryManager.class)).andReturn(dfm).anyTimes();
    EasyMock.expect(dfm.getDestinationFactory(EasyMock.isA(String.class))).andReturn(null).anyTimes();
    BindingFactoryManager bfm = control.createMock(BindingFactoryManager.class);
    EasyMock.expect(bus.getExtension(BindingFactoryManager.class)).andReturn(bfm).anyTimes();
    EasyMock.expect(bfm.getBindingFactory(EasyMock.isA(String.class))).andReturn(null).anyTimes();
    control.replay();

    int n = 19;
    services = new ServiceInfo[n];
    endpoints = new EndpointInfo[n];
    for (int i = 0; i < n; i++) {
        String resourceName = "/attachment/wsdl11/test" + i + ".wsdl";
        URL url = Wsdl11AttachmentPolicyProviderTest.class.getResource(resourceName);
        try {
            services[i] = builder.buildServices(manager.getDefinition(url.toString())).get(0);
        } catch (WSDLException ex) {
            ex.printStackTrace();
            fail("Failed to build service from resource " + resourceName);
        }
        assertNotNull(services[i]);
        endpoints[i] = services[i].getEndpoints().iterator().next();
        assertNotNull(endpoints[i]);
    }

    control.verify();

}
 
Example 15
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 16
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 17
Source File: FileDbTest.java    From MOE with Apache License 2.0 5 votes vote down vote up
public void testMakeDbFromFile() throws Exception {
  IMocksControl control = EasyMock.createControl();
  FileSystem filesystem = control.createMock(FileSystem.class);
  File dbFile = new File("/path/to/db");
  FileDb.Factory factory = new FileDb.Factory(filesystem, GsonModule.provideGson());
  String dbText =
      Joiner.on("\n")
          .join(
              "{",
              "  'equivalences': [",
              "    {",
              "      'rev1': {",
              "        'revId': 'r1',",
              "        'repositoryName': 'name1'",
              "      },",
              "      'rev2': {",
              "        'revId': 'r2',",
              "        'repositoryName': 'name2'",
              "      }",
              "    }",
              "  ]",
              "}",
              "");

  expect(filesystem.fileToString(dbFile)).andReturn(dbText);
  expect(filesystem.exists(dbFile)).andReturn(true);

  control.replay();
  assertThat(factory.load(dbFile.toPath()).getEquivalences())
      .isEqualTo(parseJson(dbFile.getPath(), dbText).getEquivalences());
  control.verify();
}
 
Example 18
Source File: ProtocolTrackerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testLifecycle() throws Exception {
   IMocksControl c = EasyMock.createControl();
   BundleContext context = c.createMock(BundleContext.class);
   String[] requiredProtocols = {"a", "b"};
   ServerTrackerCallBack callback = c.createMock(ServerTrackerCallBack.class);

   RefFact protA = new RefFact(c, context, new String[]{"a"});
   RefFact protB = new RefFact(c, context, new String[]{"b"});

   callback.addFactory(protA.factory);
   EasyMock.expectLastCall();

   callback.addFactory(protB.factory);
   EasyMock.expectLastCall();
   callback.start();
   EasyMock.expectLastCall();

   callback.removeFactory(protA.factory);
   EasyMock.expectLastCall();
   callback.stop();
   EasyMock.expectLastCall();

   c.replay();
   ProtocolTracker tracker = new ProtocolTracker("test", context, requiredProtocols, callback);
   tracker.addingService(protA.ref);
   tracker.addingService(protB.ref);
   tracker.removedService(protA.ref, protA.factory);
   c.verify();
}
 
Example 19
Source File: RepositoryContentConsumersTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testExecution()
    throws Exception
{
    IMocksControl knownControl = createNiceControl();

    RepositoryContentConsumers consumers = lookupRepositoryConsumers();
    KnownRepositoryContentConsumer selectedKnownConsumer =
        knownControl.createMock( KnownRepositoryContentConsumer.class );

    KnownRepositoryContentConsumer unselectedKnownConsumer =
        createNiceControl().createMock( KnownRepositoryContentConsumer.class );

    consumers.setApplicationContext(
        new MockApplicationContext( Arrays.asList( selectedKnownConsumer, unselectedKnownConsumer ), null ) );

    consumers.setSelectedKnownConsumers( Collections.singletonList( selectedKnownConsumer ) );

    IMocksControl invalidControl = createControl();

    InvalidRepositoryContentConsumer selectedInvalidConsumer =
        invalidControl.createMock( InvalidRepositoryContentConsumer.class );

    InvalidRepositoryContentConsumer unselectedInvalidConsumer =
        createControl().createMock( InvalidRepositoryContentConsumer.class );

    consumers.setApplicationContext(
        new MockApplicationContext( null, Arrays.asList( selectedInvalidConsumer, unselectedInvalidConsumer ) ) );

    consumers.setSelectedInvalidConsumers( Collections.singletonList( selectedInvalidConsumer ) );

    ManagedRepository repo = createRepository( "id", "name", Paths.get( "target/test-repo" ) );
    Path testFile = Paths.get( "target/test-repo/path/to/test-file.txt" );

    Date startTime = new Date( System.currentTimeMillis() );
    startTime.setTime( 12345678 );

    selectedKnownConsumer.beginScan( repo, startTime, false );
    expect( selectedKnownConsumer.getIncludes() ).andReturn( Collections.singletonList( "**/*.txt" ) );
    selectedKnownConsumer.processFile( _OS( "path/to/test-file.txt" ), false );

    knownControl.replay();

    selectedInvalidConsumer.beginScan( repo, startTime, false );
    invalidControl.replay();

    consumers.executeConsumers( repo, testFile, true );

    knownControl.verify();
    invalidControl.verify();

    knownControl.reset();
    invalidControl.reset();

    Path notIncludedTestFile = Paths.get( "target/test-repo/path/to/test-file.xml" );

    selectedKnownConsumer.beginScan( repo, startTime, false );
    expect( selectedKnownConsumer.getExcludes() ).andReturn( Collections.<String>emptyList() );

    expect( selectedKnownConsumer.getIncludes() ).andReturn( Collections.singletonList( "**/*.txt" ) );

    knownControl.replay();

    selectedInvalidConsumer.beginScan( repo, startTime, false );
    selectedInvalidConsumer.processFile( _OS( "path/to/test-file.xml" ), false );
    expect( selectedInvalidConsumer.getId() ).andReturn( "invalid" );
    invalidControl.replay();

    consumers.executeConsumers( repo, notIncludedTestFile, true );

    knownControl.verify();
    invalidControl.verify();

    knownControl.reset();
    invalidControl.reset();

    Path excludedTestFile = Paths.get( "target/test-repo/path/to/test-file.txt" );

    selectedKnownConsumer.beginScan( repo, startTime, false );
    expect( selectedKnownConsumer.getExcludes() ).andReturn( Collections.singletonList( "**/test-file.txt" ) );
    knownControl.replay();

    selectedInvalidConsumer.beginScan( repo, startTime, false );
    selectedInvalidConsumer.processFile( _OS( "path/to/test-file.txt" ), false );
    expect( selectedInvalidConsumer.getId() ).andReturn( "invalid" );
    invalidControl.replay();

    consumers.executeConsumers( repo, excludedTestFile, true );

    knownControl.verify();
    invalidControl.verify();
}
 
Example 20
Source File: JdbcTest.java    From tddl5 with Apache License 2.0 4 votes vote down vote up
public void test() {
    IMocksControl control = EasyMock.createControl();

    DBUtility mockDBUtility = control.createMock(DBUtility.class);
    Connection mockConnection = control.createMock(Connection.class);
    Statement mockStatement = control.createMock(Statement.class);
    ResultSet mockResultSet = control.createMock(ResultSet.class);

    try {
        mockDBUtility.getConnection();
        EasyMock.expectLastCall().andStubReturn(mockConnection);

        mockConnection.createStatement();
        EasyMock.expectLastCall().andStubReturn(mockStatement);

        mockStatement.executeQuery(SQLEquals.sqlEquals("SELECT * FROM sales_order_table"));
        EasyMock.expectLastCall().andStubReturn(mockResultSet);

        mockResultSet.next();
        EasyMock.expectLastCall().andReturn(true).times(3);
        EasyMock.expectLastCall().andReturn(false).times(1);

        mockResultSet.getString(1);
        EasyMock.expectLastCall().andReturn("DEMO_ORDER_001").times(1);
        EasyMock.expectLastCall().andReturn("DEMO_ORDER_002").times(1);
        EasyMock.expectLastCall().andReturn("DEMO_ORDER_003").times(1);

        mockResultSet.getString(2);
        EasyMock.expectLastCall().andReturn("Asia Pacific").times(1);
        EasyMock.expectLastCall().andReturn("Europe").times(1);
        EasyMock.expectLastCall().andReturn("America").times(1);

        mockResultSet.getDouble(3);
        EasyMock.expectLastCall().andReturn(350.0).times(1);
        EasyMock.expectLastCall().andReturn(1350.0).times(1);
        EasyMock.expectLastCall().andReturn(5350.0).times(1);

        control.replay();

        Connection conn = mockDBUtility.getConnection();
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("select * from sales_order_table");

        int i = 0;
        String[] priceLevels = { "Level_A", "Level_C", "Level_E" };
        while (rs.next()) {
            SalesOrder order = new SalesOrderImpl();
            order.loadDataFromDB(rs);
            assertEquals(order.getPriceLevel(), priceLevels[i]);
            i++;
        }

        control.verify();

    } catch (Exception e) {
        e.printStackTrace();
    }
}