Java Code Examples for org.easymock.EasyMock#createControl()

The following examples show how to use org.easymock.EasyMock#createControl() . 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: KinesisConnectorRecordProcessorTests.java    From amazon-kinesis-connectors with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() {
    // control object used to create mock dependencies
    control = EasyMock.createControl();

    // mock dependencies
    emitter = control.createMock(IEmitter.class);
    transformer = control.createMock(ITransformer.class);
    buffer = control.createMock(IBuffer.class);
    filter = control.createMock(IFilter.class);
    checkpointer = control.createMock(IRecordProcessorCheckpointer.class);
    // use a real configuration to get actual default values (not anything created by EasyMock)
    configuration = new KinesisConnectorConfiguration(new Properties(), new DefaultAWSCredentialsProviderChain());

}
 
Example 2
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 3
Source File: ArchivaServletAuthenticatorTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp()
    throws Exception
{
    super.setUp();

    httpServletRequestControl = EasyMock.createControl( );
    request = httpServletRequestControl.createMock( HttpServletRequest.class );

    setupRepository( "corporate" );
}
 
Example 4
Source File: CassandraMetadataRepositoryTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp()
    throws Exception
{

    super.setUp();
    assertMaxTries =1;
    assertRetrySleepMs=10;

    Path directory = Paths.get( "target/test-repositories" );
    if ( Files.exists(directory) )
    {
        org.apache.archiva.common.utils.FileUtils.deleteDirectory( directory );
    }

    List<MetadataFacetFactory> factories = createTestMetadataFacetFactories();
    MetadataService metadataService = new MetadataService( );
    metadataService.setMetadataFacetFactories( factories );

    this.cmr = new CassandraMetadataRepository( metadataService, cassandraArchivaManager );

    sessionFactoryControl = EasyMock.createControl( );
    sessionFactory = sessionFactoryControl.createMock( RepositorySessionFactory.class );
    sessionControl = EasyMock.createControl( );
    session = sessionControl.createMock( RepositorySession.class );

    EasyMock.expect( sessionFactory.createSession( ) ).andStubReturn( session );

    sessionFactoryControl.replay();

    clearReposAndNamespace( cassandraArchivaManager );
}
 
Example 5
Source File: CachedStreamTestBase.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUseBusProps() throws Exception {
    Bus oldbus = BusFactory.getThreadDefaultBus(false);
    try {
        Object cache = createCache(64);
        File tmpfile = getTmpFile("Hello World!", cache);
        assertNull("expects no tmp file", tmpfile);
        close(cache);

        IMocksControl control = EasyMock.createControl();

        Bus b = control.createMock(Bus.class);
        EasyMock.expect(b.getProperty(CachedConstants.THRESHOLD_BUS_PROP)).andReturn("4");
        EasyMock.expect(b.getProperty(CachedConstants.MAX_SIZE_BUS_PROP)).andReturn(null);
        EasyMock.expect(b.getProperty(CachedConstants.CIPHER_TRANSFORMATION_BUS_PROP)).andReturn(null);
        Path tmpDirPath = Files.createTempDirectory("temp-dir");
        EasyMock.expect(b.getProperty(CachedConstants.OUTPUT_DIRECTORY_BUS_PROP)).andReturn(tmpDirPath.toString());

        BusFactory.setThreadDefaultBus(b);

        control.replay();

        cache = createCache();
        tmpfile = getTmpFile("Hello World!", cache);
        assertEquals(tmpfile.getParent(), tmpDirPath.toString());
        assertNotNull("expects a tmp file", tmpfile);
        assertTrue("expects a tmp file", tmpfile.exists());
        close(cache);
        assertFalse("expects no tmp file", tmpfile.exists());

        control.verify();
    } finally {
        BusFactory.setThreadDefaultBus(oldbus);
    }
}
 
Example 6
Source File: JAASLoginInterceptorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private X509Certificate createTestCert(String subjectDn) {
    IMocksControl c = EasyMock.createControl();
    X509Certificate cert = c.createMock(X509Certificate.class);
    Principal principal = c.createMock(Principal.class);
    EasyMock.expect(principal.getName()).andReturn(subjectDn);
    EasyMock.expect(cert.getSubjectDN()).andReturn(principal);
    c.replay();
    return cert;
}
 
Example 7
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 8
Source File: FilterDispatchIntegrationTest.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public final void setUp() {
    inits = 0;
    doFilters = 0;
    destroys = 0;
    control = EasyMock.createControl();
    DaggerFilter.reset();
}
 
Example 9
Source File: GatewayForwardingServletTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedirectDefaults() throws ServletException, IOException {
  IMocksControl mockControl = EasyMock.createControl();
  ServletConfig config = mockControl.createMock(ServletConfig.class);
  ServletContext context = mockControl.createMock(ServletContext.class);
  HttpServletRequest request = mockControl.createMock(HttpServletRequest.class);
  HttpServletResponse response = mockControl.createMock(HttpServletResponse.class);
  RequestDispatcher dispatcher = mockControl.createMock(RequestDispatcher.class);
  // setup expectations
  EasyMock.expect(config.getServletName()).andStubReturn("default");
  EasyMock.expect(config.getServletContext()).andStubReturn(context);
  EasyMock.expect(config.getInitParameter("redirectTo")).andReturn("/gateway/sandbox");
  EasyMock.expect(request.getMethod()).andReturn("GET").anyTimes();
  EasyMock.expect(request.getPathInfo()).andReturn("/webhdfs/v1/tmp").anyTimes();
  EasyMock.expect(request.getQueryString()).andReturn("op=LISTSTATUS");
  EasyMock.expect(response.getStatus()).andReturn(200).anyTimes();
  EasyMock.expect(context.getContext("/gateway/sandbox")).andReturn(context);
  EasyMock.expect(context.getRequestDispatcher("/webhdfs/v1/tmp?op=LISTSTATUS")).andReturn(dispatcher);
  dispatcher.forward(request, response);
  EasyMock.expectLastCall().once();
  // logging
  context.log(EasyMock.anyObject());
  EasyMock.expectLastCall().anyTimes();
  // run the test
  mockControl.replay();
  GatewayForwardingServlet servlet = new GatewayForwardingServlet();
  servlet.init(config);
  servlet.service(request, response);
  mockControl.verify();
}
 
Example 10
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 11
Source File: NewArtifactsRssFeedProcessorTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp()
    throws Exception
{
    super.setUp();

    newArtifactsProcessor = new NewArtifactsRssFeedProcessor();
    newArtifactsProcessor.setGenerator( new RssFeedGenerator() );

    metadataRepository = new MetadataRepositoryMock();

    sessionFactoryControl = EasyMock.createControl();
    sessionControl = EasyMock.createControl();
    sessionControl.resetToNice();

    sessionFactory = sessionFactoryControl.createMock( RepositorySessionFactory.class );
    session = sessionControl.createMock( RepositorySession.class );

    EasyMock.expect( sessionFactory.createSession() ).andStubReturn( session );
    EasyMock.expect( session.getRepository( ) ).andStubReturn( metadataRepository );

    sessionFactoryControl.replay();
    sessionControl.replay();

    newArtifactsProcessor.setRepositorySessionFactory( sessionFactory );

}
 
Example 12
Source File: BaseMockTest.java    From jparsec with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  replayed = false;
  control = EasyMock.createControl();
  for (Field field : getMockFields(getClass())) {
    field.set(this, mock(field.getType()));
  }
}
 
Example 13
Source File: LockCleanerRunnableTest.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Before
public void setupMocks() {
    relaxedCtrl = EasyMock.createControl();
    tx = relaxedCtrl.createMock(StoreTransaction.class);

    ctrl = EasyMock.createStrictControl();
    store = ctrl.createMock(KeyColumnValueStore.class);
}
 
Example 14
Source File: AbstractMavenRepositorySearch.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp()
    throws Exception
{
    super.setUp();

    FileUtils.deleteDirectory( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_1 + "/.indexer" ) );
    assertFalse( Files.exists(Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_1 + "/.indexer" )) );

    FileUtils.deleteDirectory( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_2 + "/.indexer" ) );
    assertFalse( Files.exists(Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_2 + "/.indexer" )) );

    archivaConfigControl = EasyMock.createControl();

    archivaConfig = archivaConfigControl.createMock( ArchivaConfiguration.class );

    repositoryRegistry.setArchivaConfiguration( archivaConfig );

    search = new MavenRepositorySearch( indexer, repositoryRegistry, proxyRegistry,
                                        queryCreator );

    assertNotNull( repositoryRegistry );

    config = new Configuration();
    config.addManagedRepository( createRepositoryConfig( TEST_REPO_1 ) );
    config.addManagedRepository( createRepositoryConfig( TEST_REPO_2 ) );
    config.addManagedRepository( createRepositoryConfig( REPO_RELEASE ) );

    archivaConfig.addListener( EasyMock.anyObject( ConfigurationListener.class ) );
    EasyMock.expect( archivaConfig.getDefaultLocale() ).andReturn( Locale.getDefault( ) ).anyTimes();
    EasyMock.expect( archivaConfig.getConfiguration() ).andReturn(config).anyTimes();
    archivaConfig.save(EasyMock.anyObject(Configuration.class));
    EasyMock.expectLastCall().anyTimes();
    archivaConfigControl.replay();
    repositoryRegistry.reload();

}
 
Example 15
Source File: ProcessFacadeImplTest.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() {
  control = EasyMock.createControl();
  equipmentFacade = control.createMock(EquipmentFacade.class);
  processCache = control.createMock(ProcessCache.class);
  subEquipmentFacade = control.createMock(SubEquipmentFacade.class);
  aliveTimerFacade = control.createMock(AliveTimerFacade.class);
  aliveTimerCache = control.createMock(AliveTimerCache.class);
  processFacade = new ProcessFacadeImpl(equipmentFacade, processCache, subEquipmentFacade, aliveTimerCache, aliveTimerFacade, new ServerProperties());
}
 
Example 16
Source File: BasicMemoryBufferTests.java    From amazon-kinesis-connectors with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    // Setup the config
    Properties props = new Properties();
    props.setProperty(KinesisConnectorConfiguration.PROP_BUFFER_RECORD_COUNT_LIMIT,
            Integer.toString(buffRecCount));
    props.setProperty(KinesisConnectorConfiguration.PROP_BUFFER_BYTE_SIZE_LIMIT,
            Integer.toString(buffByteLim));
    props.setProperty(KinesisConnectorConfiguration.PROP_BUFFER_MILLISECONDS_LIMIT,
            Long.toString(buffTimeMilliLim));
    config = new KinesisConnectorConfiguration(props, new DefaultAWSCredentialsProviderChain());

    control = EasyMock.createControl();

}
 
Example 17
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 18
Source File: NetworkRouteTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Before
public void before() throws Exception {
   control = EasyMock.createControl();
   localBroker = control.createMock(Transport.class);
   remoteBroker = control.createMock(Transport.class);

   NetworkBridgeConfiguration configuration = new NetworkBridgeConfiguration();
   brokerService = new BrokerService();
   BrokerInfo remoteBrokerInfo = new BrokerInfo();

   configuration.setDuplex(true);
   configuration.setNetworkTTL(5);
   brokerService.setBrokerId("broker-1");
   brokerService.setPersistent(false);
   brokerService.setUseJmx(false);
   brokerService.start();
   brokerService.waitUntilStarted();
   remoteBrokerInfo.setBrokerId(new BrokerId("remote-broker-id"));
   remoteBrokerInfo.setBrokerName("remote-broker-name");

   localBroker.setTransportListener(EasyMock.isA(TransportListener.class));
   ArgHolder localListenerRef = ArgHolder.holdArgsForLastVoidCall();

   remoteBroker.setTransportListener(EasyMock.isA(TransportListener.class));
   ArgHolder remoteListenerRef = ArgHolder.holdArgsForLastVoidCall();
   localBroker.start();
   remoteBroker.start();

   remoteBroker.oneway(EasyMock.isA(Object.class));
   EasyMock.expectLastCall().times(4);
   remoteBroker.oneway(EasyMock.isA(Object.class));
   ExpectationWaiter remoteInitWaiter = ExpectationWaiter.waiterForLastVoidCall();

   localBroker.oneway(remoteBrokerInfo);
   EasyMock.expect(localBroker.request(EasyMock.isA(Object.class))).andReturn(null);
   localBroker.oneway(EasyMock.isA(Object.class));
   ExpectationWaiter localInitWaiter = ExpectationWaiter.waiterForLastVoidCall();

   control.replay();

   DurableConduitBridge bridge = new DurableConduitBridge(configuration, localBroker, remoteBroker);
   bridge.setBrokerService(brokerService);
   bridge.start();

   localListener = (TransportListener) localListenerRef.getArguments()[0];
   Assert.assertNotNull(localListener);
   remoteListener = (TransportListener) remoteListenerRef.getArguments()[0];
   Assert.assertNotNull(remoteListener);

   remoteListener.onCommand(remoteBrokerInfo);

   remoteInitWaiter.assertHappens(5, TimeUnit.SECONDS);
   localInitWaiter.assertHappens(5, TimeUnit.SECONDS);

   control.verify();
   control.reset();

   ActiveMQMessage msg = new ActiveMQMessage();
   msg.setDestination(new ActiveMQTopic("test"));
   msgDispatch = new MessageDispatch();
   msgDispatch.setMessage(msg);

   ConsumerInfo path1 = new ConsumerInfo();
   path1.setDestination(msg.getDestination());
   path1.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-1"), 1), 3));
   path1.setBrokerPath(new BrokerId[]{new BrokerId("remote-broker-id"), new BrokerId("server(1)-broker-id"),});
   path1Msg = new ActiveMQMessage();
   path1Msg.setDestination(AdvisorySupport.getConsumerAdvisoryTopic(path1.getDestination()));
   path1Msg.setDataStructure(path1);

   ConsumerInfo path2 = new ConsumerInfo();
   path2.setDestination(path1.getDestination());
   path2.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-2"), 2), 4));
   path2.setBrokerPath(new BrokerId[]{new BrokerId("remote-broker-id"), new BrokerId("server(2)-broker-id"), new BrokerId("server(1)-broker-id"),});
   path2Msg = new ActiveMQMessage();
   path2Msg.setDestination(path1Msg.getDestination());
   path2Msg.setDataStructure(path2);

   RemoveInfo removePath1 = new RemoveInfo(path1.getConsumerId());
   RemoveInfo removePath2 = new RemoveInfo(path2.getConsumerId());

   removePath1Msg = new ActiveMQMessage();
   removePath1Msg.setDestination(path1Msg.getDestination());
   removePath1Msg.setDataStructure(removePath1);

   removePath2Msg = new ActiveMQMessage();
   removePath2Msg.setDestination(path1Msg.getDestination());
   removePath2Msg.setDataStructure(removePath2);
}
 
Example 19
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();
    }
}
 
Example 20
Source File: TestabilityLauncherTest.java    From testability-explorer with Apache License 2.0 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
  launcher = new TestabilityLauncher();
  control = EasyMock.createControl();
  javaProject = control.createMock(IJavaProject.class);
}