Java Code Examples for org.easymock.IAnswer

The following examples show how to use org.easymock.IAnswer. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: arcusplatform   Source File: TestForEachModelAction.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOneMatchingModel() {
   final RuleContext namespacedContext = new NamespaceContext(model1.getId(), context);
   mockAction.execute(namespacedContext);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model1.getAddress(), namespacedContext.getVariable(targetVariable));
         return ActionState.FIRING;
      }
   });
   
   EasyMock.replay(mockAction);
   
   ForEachModelAction selector = new ForEachModelAction(mockAction, Predicates.<Model>alwaysTrue(), Predicates.<Model>equalTo(model1), "address");
   selector.execute(context);
   assertNull(context.getVariable(targetVariable));
   assertEquals(ImmutableList.<Address>of(model1.getAddress()),context.getVariable(ForEachModelAction.VAR_STILL_FIRING));
   EasyMock.verify(mockAction);
}
 
Example 2
Source Project: arcusplatform   Source File: TestForEachModelAction.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOneMatchingModel() {
   mockAction.execute(context);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model1.getAddress(), context.getVariable(targetVariable));
         return null;
      }
   });
   
   EasyMock.replay(mockAction);
   
   ForEachModelAction selector = new ForEachModelAction(mockAction, Predicates.<Model>equalTo(model1), "address");
   selector.execute(context);
   assertNull(context.getVariable(targetVariable));
   
   EasyMock.verify(mockAction);
}
 
Example 3
Source Project: arcusplatform   Source File: TestCallTree.java    License: Apache License 2.0 6 votes vote down vote up
private static void initEasyMockVariableSupport(final SubsystemContext<? extends SubsystemModel> context){
   // basically this is implementing variable support
   final Capture<String> nameRef = EasyMock.newCapture(CaptureType.LAST);
   final Capture<Object> valueRef = EasyMock.newCapture(CaptureType.LAST);
   EasyMock
      .expect(context.getVariable(EasyMock.capture(nameRef)))
      .andAnswer(new IAnswer<LooselyTypedReference>() {
         @Override
         public LooselyTypedReference answer() throws Throwable {
            String json = context.model().getAttribute(TypeMarker.string(), "_subvars:" + nameRef.getValue(), "null");
            return JSON.fromJson(json, LooselyTypedReference.class);
         }
      })
      .anyTimes();
   context.setVariable(EasyMock.capture(nameRef), EasyMock.capture(valueRef));
   EasyMock
      .expectLastCall()
      .andAnswer(new IAnswer<Object>() {
         @Override
         public Object answer() throws Throwable {
            context.model().setAttribute("_subvars:" + nameRef.getValue(), JSON.toJson(valueRef.getValue()));
            return null;
         }
      })
      .anyTimes();
}
 
Example 4
Source Project: arcusplatform   Source File: TestSetAttributes.java    License: Apache License 2.0 6 votes vote down vote up
private void setupUpdateEmail(String newEmail) {

   	personDao.setUpdateFlag(person.getId(), true);
   	EasyMock.expectLastCall();
   	EasyMock.expect(personDao.updatePersonAndEmail(person, person.getEmail())).andAnswer(new IAnswer<Person>() {

			@Override
			public Person answer() throws Throwable {
				Person newPerson = person.copy();
				newPerson.setEmail(newEmail);
				return newPerson;
			}
		});

   	personDao.setUpdateFlag(person.getId(), false);
   	EasyMock.expectLastCall();
   	EasyMock.expect(personPlaceAssocDao.findPlaceIdsByPerson(person.getId())).andReturn(ImmutableSet.<UUID>of(firstPlace.getId()));		
	}
 
Example 5
Source Project: saros   Source File: ArrayUtilsTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Before
public void createMock() {
  adapterManager = EasyMock.createMock(IAdapterManager.class);
  EasyMock.expect(
          adapterManager.getAdapter(EasyMock.anyObject(), EasyMock.anyObject(Class.class)))
      .andAnswer(
          new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
              return EasyMock.getCurrentArguments()[0];
            }
          })
      .anyTimes();

  EasyMock.replay(adapterManager);
}
 
Example 6
Source Project: proarc   Source File: TiffImporterTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
private DaoFactory createMockDaoFactory() {
    DaoFactory daos = EasyMock.createMock(DaoFactory.class);
    EasyMock.expect(daos.createTransaction()).andAnswer(new IAnswer<Transaction>() {

        @Override
        public Transaction answer() throws Throwable {
            return createMockTransaction();
        }
    }).anyTimes();
    EasyMock.expect(daos.createBatchItem()).andAnswer(new IAnswer<BatchItemDao>() {

        @Override
        public BatchItemDao answer() throws Throwable {
            return createMockBatchItemDao();
        }
    }).anyTimes();
    EasyMock.replay(daos);
    toVerify.add(daos);
    return daos;
}
 
Example 7
Source Project: proarc   Source File: WaveImporterTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
private DaoFactory createMockDaoFactory() {
    DaoFactory daos = EasyMock.createMock(DaoFactory.class);
    EasyMock.expect(daos.createTransaction()).andAnswer(new IAnswer<Transaction>() {

        @Override
        public Transaction answer() throws Throwable {
            return createMockTransaction();
        }
    }).anyTimes();
    EasyMock.expect(daos.createBatchItem()).andAnswer(new IAnswer<BatchItemDao>() {

        @Override
        public BatchItemDao answer() throws Throwable {
            return createMockBatchItemDao();
        }
    }).anyTimes();
    EasyMock.replay(daos);
    toVerify.add(daos);
    return daos;
}
 
Example 8
Source Project: ormlite-core   Source File: MappedCreateTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testArgumentHolderSetZero() throws Exception {
	TableInfo<Foo, Integer> tableInfo = new TableInfo<Foo, Integer>(databaseType, Foo.class);
	Dao<Foo, Integer> dao = createDao(Foo.class, false);
	MappedCreate<Foo, Integer> mappedCreate = MappedCreate.build(dao, tableInfo);
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(conn.insert(isA(String.class), isA(Object[].class), isA(FieldType[].class),
			isA(GeneratedKeyHolder.class))).andAnswer(new IAnswer<Integer>() {
				@Override
				public Integer answer() throws Throwable {
					GeneratedKeyHolder holder = (GeneratedKeyHolder) getCurrentArguments()[3];
					holder.addKey((Integer) 0);
					return 1;
				}
			});
	replay(conn);
	mappedCreate.insert(databaseType, conn, new Foo(), null);
}
 
Example 9
Source Project: ormlite-core   Source File: MappedCreateTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testArgumentHolderDoubleSet() throws Exception {
	TableInfo<Foo, Integer> tableInfo = new TableInfo<Foo, Integer>(databaseType, Foo.class);
	Dao<Foo, Integer> dao = createDao(Foo.class, false);
	MappedCreate<Foo, Integer> mappedCreate = MappedCreate.build(dao, tableInfo);
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(conn.insert(isA(String.class), isA(Object[].class), isA(FieldType[].class),
			isA(GeneratedKeyHolder.class))).andAnswer(new IAnswer<Integer>() {
				@Override
				public Integer answer() throws Throwable {
					GeneratedKeyHolder holder = (GeneratedKeyHolder) getCurrentArguments()[3];
					holder.addKey((Integer) 1);
					holder.addKey((Integer) 2);
					return 1;
				}
			});
	replay(conn);
	mappedCreate.insert(databaseType, conn, new Foo(), null);
}
 
Example 10
Source Project: todo-apps   Source File: MongoStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPersist() {
	DBCollection coll = createMockCollection();
	ToDo td = new ToDo();
	td.setTitle("This is a test");
	td.setId("aaaaaaaaaaaaaaaaaaaaaaa1");
	expect(coll.insert(isA(DBObject.class))).andAnswer(new IAnswer<WriteResult>() {
		@Override
		public WriteResult answer() throws Throwable {
			DBObject obj = (DBObject)getCurrentArguments()[0];
			obj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa1"));
			return null;
		}
	});
	replay(coll);
	MongoStore store = new MongoStore(coll);
	assertEquals(td, store.persist(td));
	verify(coll);
}
 
Example 11
Source Project: cxf   Source File: LoggingInInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    loggingMessage = new LoggingMessage("", "");
    control = EasyMock.createNiceControl();

    StringWriter sw = new StringWriter();
    sw.append("<today/>");
    message = new MessageImpl();
    message.setExchange(new ExchangeImpl());
    message.put(Message.CONTENT_TYPE, "application/xml");
    message.setContent(Writer.class, sw);

    inputStream = control.createMock(InputStream.class);
    EasyMock.expect(inputStream.read(EasyMock.anyObject(byte[].class), EasyMock.anyInt(), EasyMock.anyInt()))
            .andAnswer(new IAnswer<Integer>() {
                public Integer answer() {
                    System.arraycopy(bufferContent.getBytes(), 0,
                            EasyMock.getCurrentArguments()[0], 0,
                            bufferLength);
                    return bufferLength;
                }
            }).andStubReturn(-1);
    control.replay();
}
 
Example 12
Source Project: attic-aurora   Source File: FakeScheduledExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private static IAnswer<ScheduledFuture<?>> answerScheduleAtFixedRate(
    FakeScheduledExecutor executor,
    int workCount) {

  return () -> {
    Object[] args = EasyMock.getCurrentArguments();
    Runnable work = (Runnable) args[0];
    long initialDelay = (Long) args[1];
    long period = (Long) args[2];
    TimeUnit unit = (TimeUnit) args[3];
    for (int i = 0; i <= workCount; i++) {
      addDelayedWork(executor, toMillis(initialDelay, unit) + i * toMillis(period, unit), work);
    }
    return null;
  };
}
 
Example 13
Source Project: FlowSpaceFirewall   Source File: ProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
public void setupFSFW(){
	fsfw = createMock(FlowSpaceFirewall.class);
	List<OFStatistics> stats = new ArrayList<OFStatistics>();
	proxies = new ArrayList<Proxy>();
	expect(fsfw.getStats(EasyMock.anyLong())).andReturn(stats).anyTimes();
	
	expect(fsfw.getSwitchProxies(EasyMock.anyLong())).andReturn(proxies).anyTimes();
	fsfw.removeProxy(EasyMock.anyLong(), EasyMock.isA(Proxy.class));
	EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
		public Object answer(){
			log.error("removed the proxy!");
			return null;
		}
	}).anyTimes();
	fsfw.addFlowCache(EasyMock.anyLong(), EasyMock.anyObject(String.class), EasyMock.anyObject(OFFlowMod.class), EasyMock.anyObject(List.class));
	EasyMock.expectLastCall().anyTimes();
	fsfw.delFlowCache(EasyMock.anyLong(), EasyMock.anyObject(String.class), EasyMock.anyObject(OFFlowMod.class), EasyMock.anyObject(List.class));
	EasyMock.expectLastCall().anyTimes();
	
	EasyMock.replay(fsfw);
}
 
Example 14
Source Project: attic-aurora   Source File: DurableStorageTest.java    License: Apache License 2.0 5 votes vote down vote up
private void expectPersist(Op op, Op... ops) {
  try {
    // Workaround for comparing streams.
    persistence.persist(anyObject());
    expectLastCall().andAnswer((IAnswer<Void>) () -> {
      assertEquals(
          ImmutableList.<Op>builder().add(op).add(ops).build(),
          ((Stream<Op>) EasyMock.getCurrentArguments()[0]).collect(Collectors.toList()));

      return null;
    });
  } catch (Persistence.PersistenceException e) {
    throw new RuntimeException(e);
  }
}
 
Example 15
Source Project: arcusplatform   Source File: TestForEachModelAction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleMatchingModels() {
   mockAction.execute(context);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model1.getAddress(), context.getVariable(targetVariable));
         return null;
      }
   });
   mockAction.execute(context);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model2.getAddress(), context.getVariable(targetVariable));
         return null;
      }
   });
   mockAction.execute(context);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model3.getAddress(), context.getVariable(targetVariable));
         return null;
      }
   });
   
   EasyMock.replay(mockAction);
   
   ForEachModelAction selector = new ForEachModelAction(mockAction, Predicates.<Model>alwaysTrue(), "address");
   selector.execute(context);
   assertNull(context.getVariable(targetVariable));
   
   EasyMock.verify(mockAction);
}
 
Example 16
Source Project: arcusplatform   Source File: HubAlarmSubsystemTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void expectCancelIncidentAndReturn(
		final ListenableFuture<Void> response, 
		final AlarmIncidentModel expectedIncident
) {
	EasyMock
		.expect(
				incidentService.cancel(
						EasyMock.eq(context), 
						EasyMock.eq(expectedIncident.getAddress().getRepresentation()), 
						EasyMock.isA(Address.class), 
						EasyMock.isA(String.class)
				)
		)
		.andAnswer(new IAnswer<AlarmIncidentModel>() {

			@Override
			public AlarmIncidentModel answer() throws Throwable {
				response.addListener(
						new Runnable() {
							@Override
							public void run() {
								PlatformMessage message =
										PlatformMessage
											.broadcast()
											.from(expectedIncident.getAddress())
											.withPlaceId(expectedIncident.getPlaceId())
											.withPayload(AlarmIncidentCapability.CompletedEvent.instance())
											.create();
								subsystem.onEvent(new MessageReceivedEvent(message), context);
							}
						},
						MoreExecutors.directExecutor()
				);
				return expectedIncident;
			}
		});
	EasyMock.expect(incidentService.getIncident(EasyMock.eq(context), EasyMock.isA(Address.class))).andReturn(expectedIncident);
	
}
 
Example 17
Source Project: arcusplatform   Source File: BaseAlarmSubsystemTestCase.java    License: Apache License 2.0 5 votes vote down vote up
protected void expectCancelIncidentAndReturn(
		final ListenableFuture<Void> response, 
		final AlarmIncidentModel expectedIncident
) {
	EasyMock
		.expect(
				incidentService.cancel(EasyMock.eq(context), EasyMock.isA(Address.class), EasyMock.isA(String.class))
		)
		.andAnswer(new IAnswer<AlarmIncidentModel>() {

			@Override
			public AlarmIncidentModel answer() throws Throwable {
				response.addListener(
						new Runnable() {
							@Override
							public void run() {
								PlatformMessage message =
										PlatformMessage
											.broadcast()
											.from(expectedIncident.getAddress())
											.withPlaceId(expectedIncident.getPlaceId())
											.withPayload(AlarmIncidentCapability.CompletedEvent.instance())
											.create();
								subsystem.onEvent(new MessageReceivedEvent(message), context);
							}
						},
						MoreExecutors.directExecutor()
				);
				return expectedIncident;
			}
		});
	EasyMock.expect(incidentService.getIncident(EasyMock.eq(context), EasyMock.isA(Address.class))).andReturn(expectedIncident);
	
}
 
Example 18
Source Project: saros   Source File: SarosSessionTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static IWorkspace createWorkspaceMock(final List<Object> workspaceListeners) {

    final IWorkspace workspace = createMock(IWorkspace.class);

    workspace.addResourceChangeListener(isA(IResourceChangeListener.class), anyInt());

    expectLastCall()
        .andStubAnswer(
            new IAnswer<Object>() {

              @Override
              public Object answer() throws Throwable {
                workspaceListeners.add(getCurrentArguments()[0]);
                return null;
              }
            });

    workspace.removeResourceChangeListener(isA(IResourceChangeListener.class));

    expectLastCall()
        .andStubAnswer(
            new IAnswer<Object>() {

              @Override
              public Object answer() throws Throwable {
                workspaceListeners.remove(getCurrentArguments()[0]);
                return null;
              }
            });

    replay(workspace);

    PowerMock.mockStaticPartial(ResourcesPlugin.class, "getWorkspace");
    ResourcesPlugin.getWorkspace();
    expectLastCall().andReturn(workspace).anyTimes();
    PowerMock.replay(ResourcesPlugin.class);

    return workspace;
  }
 
Example 19
Source Project: grox   Source File: StoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
//TDD for issue #13: https://github.com/groupon/grox/issues/13
public void testStore_shouldQueueActions() {
  //GIVEN
  Store<Integer> store = new Store<>(0);
  StateChangeListener<Integer> mockListener0 = createStrictMock(StateChangeListener.class);
  StateChangeListener<Integer> mockListener1 = createStrictMock(StateChangeListener.class);

  mockListener0.onStateChanged(0);

  mockListener1.onStateChanged(0);

  mockListener0.onStateChanged(-1);
  expectLastCall()
      .andAnswer(
          new IAnswer<Void>() {
            @Override
            public Void answer() throws Throwable {
              store.dispatch(integer -> 1);
              return null;
            }
          });
  mockListener1.onStateChanged(-1);

  mockListener0.onStateChanged(1);
  mockListener1.onStateChanged(1);

  replay(mockListener0, mockListener1);

  //WHEN
  store.subscribe(mockListener0);
  store.subscribe(mockListener1);

  store.dispatch(i -> -1);

  //THEN
  verify(mockListener0, mockListener1);
}
 
Example 20
Source Project: saros   Source File: EditorManagerMock.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static EditorManager createMock(final List<Object> editorListeners) {
  EditorManager editorManager = EasyMock.createMock(EditorManager.class);
  editorManager.addSharedEditorListener(EasyMock.isA(ISharedEditorListener.class));
  EasyMock.expectLastCall()
      .andAnswer(
          new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
              editorListeners.add(EasyMock.getCurrentArguments()[0]);
              return null;
            }
          })
      .anyTimes();
  editorManager.removeSharedEditorListener(EasyMock.isA(ISharedEditorListener.class));
  EasyMock.expectLastCall()
      .andAnswer(
          new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
              editorListeners.remove(EasyMock.getCurrentArguments()[0]);
              return null;
            }
          })
      .anyTimes();

  EasyMock.expect(editorManager.getOpenEditors()).andStubReturn(Collections.emptySet());
  EasyMock.replay(editorManager);
  return editorManager;
}
 
Example 21
Source Project: proarc   Source File: UserManagerSqlTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Before
    public void setUp() throws Exception {
        // fedora init
        fedora = new FedoraTestSupport();
        fedora.cleanUp();
        remoteStorage = fedora.getRemoteStorage();
        // rdbms init
        db = new DbUnitSupport();
        EmpireDaoFactory daos = new EmpireDaoFactory(db.getEmireCfg());
        daos.init();
        DataSource dataSource = EasyMock.createMock(DataSource.class);
        EasyMock.expect(dataSource.getConnection()).andAnswer(new IAnswer<Connection>() {

            @Override
            public Connection answer() throws Throwable {
                return db.getEmireCfg().getConnection();
            }
        }).anyTimes();
        IDataSet database = database(
                // XXX related fedora objects do not exist!
                db.loadFlatXmlDataStream(EmpireUserDaoTest.class, "user.xml")
//                db.loadFlatXmlDataStream(getClass(), "group.xml")
                );
        final IDatabaseConnection con = db.getConnection();
        try {
            db.cleanInsert(con, database);
            db.initSequences(con.getConnection(), 10, db.getEmireCfg().getSchema().tableUser.id.getSequenceName());
            db.initSequences(con.getConnection(), 10, db.getEmireCfg().getSchema().tableUserGroup.id.getSequenceName());
            con.getConnection().commit();
        } finally {
            con.getConnection().close();
        }

        EasyMock.replay(dataSource);
        manager = new UserManagerSql(dataSource, temp.getRoot(), remoteStorage, daos);
    }
 
Example 22
Source Project: javamelody   Source File: TestHtmlDependenciesReport.java    License: Apache License 2.0 5 votes vote down vote up
/** Test.
 * @throws IOException e */
@Test
public void testDependencies() throws IOException {
	final ServletContext context = createNiceMock(ServletContext.class);
	final String javamelodyDir = "/META-INF/maven/net.bull.javamelody/";
	final String webapp = javamelodyDir + "javamelody-test-webapp/";
	expect(context.getResourcePaths("/META-INF/maven/"))
			.andReturn(Collections.singleton(javamelodyDir)).anyTimes();
	expect(context.getResourcePaths(javamelodyDir)).andReturn(Collections.singleton(webapp))
			.anyTimes();
	final IAnswer<InputStream> answer = new IAnswer<InputStream>() {
		@Override
		public InputStream answer() throws Throwable {
			return getClass().getResourceAsStream("/pom.xml");
		}
	};
	expect(context.getResourceAsStream(webapp + "pom.xml")).andAnswer(answer).anyTimes();
	final Set<String> dependencies = new LinkedHashSet<String>(
			Arrays.asList("/WEB-INF/lib/jrobin-1.5.9.jar",
					"/WEB-INF/lib/javamelody-core-1.65.0.jar", "/WEB-INF/lib/nothing.jar"));
	expect(context.getResourcePaths("/WEB-INF/lib/")).andReturn(dependencies).anyTimes();
	expect(context.getMajorVersion()).andReturn(2).anyTimes();
	expect(context.getMinorVersion()).andReturn(5).anyTimes();
	replay(context);
	Parameters.initialize(context);
	final Map<String, MavenArtifact> webappDependencies = MavenArtifact.getWebappDependencies();
	assertFalse("getWebappDependencies", webappDependencies.isEmpty());
	verify(context);

	final StringWriter writer = new StringWriter();
	final HtmlDependenciesReport htmlDependenciesReport = new HtmlDependenciesReport(
			webappDependencies, writer);
	htmlDependenciesReport.toHtml();
	assertNotEmptyAndClear(writer);
}
 
Example 23
Source Project: activemq-artemis   Source File: NetworkRouteTest.java    License: Apache License 2.0 5 votes vote down vote up
public static ArgHolder holdArgsForLastVoidCall() {
   final ArgHolder holder = new ArgHolder();
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         Object[] args = EasyMock.getCurrentArguments();
         holder.arguments = Arrays.copyOf(args, args.length);
         return null;
      }
   });
   return holder;
}
 
Example 24
Source Project: activemq-artemis   Source File: NetworkRouteTest.java    License: Apache License 2.0 5 votes vote down vote up
public static ArgHolder holdArgsForLastObjectCall() {
   final ArgHolder holder = new ArgHolder();
   EasyMock.expect(new Object()).andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         Object[] args = EasyMock.getCurrentArguments();
         holder.arguments = Arrays.copyOf(args, args.length);
         return null;
      }
   });
   return holder;
}
 
Example 25
Source Project: activemq-artemis   Source File: NetworkRouteTest.java    License: Apache License 2.0 5 votes vote down vote up
public static ArgHolder holdArgsForLastFutureRequestCall() {
   final ArgHolder holder = new ArgHolder();
   EasyMock.expect(new FutureResponse(null)).andAnswer(new IAnswer<FutureResponse>() {
      @Override
      public FutureResponse answer() throws Throwable {
         Object[] args = EasyMock.getCurrentArguments();
         holder.arguments = Arrays.copyOf(args, args.length);
         return null;
      }
   });

   return holder;
}
 
Example 26
Source Project: activemq-artemis   Source File: NetworkRouteTest.java    License: Apache License 2.0 5 votes vote down vote up
public static ExpectationWaiter waiterForLastVoidCall() {
   final ExpectationWaiter waiter = new ExpectationWaiter();
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         waiter.latch.countDown();
         return null;
      }
   });
   return waiter;
}
 
Example 27
Source Project: gameserver   Source File: MessageTransferHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
	public void testMessageReceivedIoSessionObject() throws Exception {
		MessageTransferHandler handler = new MessageTransferHandler();

		final IoSession userSession = createMock(IoSession.class);
		expect(userSession.isConnected()).andReturn(Boolean.TRUE);
		
		final MessageQueue messageQueue = createMock(MessageQueue.class);
		
		expect(messageQueue.findSession(anyObject(SessionKey.class))).andReturn(userSession);
		
		messageQueue.sessionWrite(anyObject(SessionKey.class), anyObject());
		expectLastCall().andAnswer(new IAnswer<Object>() {
			@Override
			public Object answer() throws Throwable {
				SessionKey tmpSessionKey = (SessionKey)getCurrentArguments()[0];
				IoBuffer tmpBuf = (IoBuffer)getCurrentArguments()[1];
				assertEquals("7F00000100003039", tmpSessionKey.toString().substring(0, 16));
				assertEquals(40, tmpBuf.array().length);
//				System.out.println(msg);
				return null;
			}
		});
		
		TestUtil.setPrivateFieldValue("messageQueue", handler, messageQueue);
		
		replay(messageQueue);
		replay(userSession);
		
		SessionRawMessage message = createSessionRawMessage(40);
		handler.messageReceived(null, message);
		
		verify(messageQueue);
		verify(userSession);
		
	}
 
Example 28
Source Project: gameserver   Source File: BceLoginHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSessionNotFoundUser() throws Exception {
	String userName = randomUserName();
	
	BceLogin.Builder payload = BceLogin.getDefaultInstance().newBuilderForType();
	payload.setUsername(userName);
	payload.setPassword("000000");
	BceLogin msg = payload.build();
	
	XinqiMessage message = new XinqiMessage();
	message.index = 1;
	message.type = MessageToId.messageToId(msg);
	message.payload = msg;
	
	BceLoginHandler handler = BceLoginHandler.getInstance();
	
	IoSession session = createMock(IoSession.class);
	
	expect(session.write(anyObject())).andAnswer(new IAnswer<WriteFuture>(){
		@Override
		public WriteFuture answer() throws Throwable {
			XinqiMessage response = (XinqiMessage)getCurrentArguments()[0];
			BseLogin login = (BseLogin)response.payload;
			assertEquals(ErrorCode.NOTFOUND.ordinal(), login.getCode());
			return null;
		}
	}).times(1);

	replay(session);
	
	handler.messageProcess(session, message, null);
	
	verify(session);
}
 
Example 29
Source Project: gameserver   Source File: BceLoginHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private void registerUser(String userName) throws Exception {
	BceRegister.Builder payload = BceRegister.getDefaultInstance().newBuilderForType();
	payload.setUsername(userName);
	payload.setPassword("000000");
	BceRegister msg = payload.build();
	
	XinqiMessage message = new XinqiMessage();
	message.index = 1;
	message.type = MessageToId.messageToId(msg);
	message.payload = msg;
	
	BceRegisterHandler handler = BceRegisterHandler.getInstance();
	
	IoSession session = createMock(IoSession.class);
	
	session.write(anyObject());
	
	expectLastCall().andAnswer(new IAnswer<Object>() {
		public Object answer() {
			XinqiMessage response = (XinqiMessage)getCurrentArguments()[0];
			XinqiBseRegister.BseRegister register = (XinqiBseRegister.BseRegister)response.payload;
			assertEquals(LoginManager.RegisterErrorCode.SUCCESS.ordinal(), register.getCode());
			return null;
		}
	});
	
	replay(session);
	
	handler.messageProcess(session, message, null);
	
	verify(session);
}
 
Example 30
Source Project: gameserver   Source File: BceLoginHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private void registerUser2(String userName) throws Exception {
	BceRegister.Builder payload = BceRegister.getDefaultInstance().newBuilderForType();
	payload.setUsername(userName);
	payload.setPassword("000000");
	BceRegister msg = payload.build();
	
	XinqiMessage message = new XinqiMessage();
	message.index = 1;
	message.type = MessageToId.messageToId(msg);
	message.payload = msg;
	
	BceRegisterHandler handler = BceRegisterHandler.getInstance();
	
	IoSession session = createMock(IoSession.class);
	
	session.write(anyObject());
	expectLastCall().andAnswer(new IAnswer<Object>() {
		public Object answer() {
			return null;
		}
	});
	
	replay(session);
	
	handler.messageProcess(session, message, null);
	
	verify(session);
}