Java Code Examples for org.easymock.EasyMock

The following are top voted examples for showing how to use org.easymock.EasyMock. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: athena   File: OspfNbrImplTest.java   View source code 6 votes vote down vote up
/**
 * Tests adjOk() method.
 */
@Test
public void testAdjOk() throws Exception {
    channel = EasyMock.createMock(Channel.class);
    ospfInterface.setInterfaceType(OspfInterfaceType.BROADCAST.value());
    ospfInterface.setIpAddress(Ip4Address.valueOf("2.2.2.2"));
    ospfNbr1 = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("1.1.1.1"),
                               Ip4Address.valueOf("2.2.2.2"), 2,
                               topologyForDeviceAndLink);
    ospfNbr1.setState(OspfNeighborState.TWOWAY);
    ospfNbr1.setNeighborDr(Ip4Address.valueOf("2.2.2.2"));
    ospfNbr1.adjOk(channel);
    assertThat(ospfNbr1, is(notNullValue()));

    ospfInterface.setInterfaceType(OspfInterfaceType.POINT_TO_POINT.value());
    ospfNbr1 = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("1.1.1.1"),
                               Ip4Address.valueOf("2.2.2.2"), 2,
                               topologyForDeviceAndLink);
    channel = null;
    channel = EasyMock.createMock(Channel.class);
    ospfNbr1.adjOk(channel);
    assertThat(ospfNbr1, is(notNullValue()));
}
 
Example 2
Project: intellij-deps-ini4j   File: IniParserTest.java   View source code 6 votes vote down vote up
@Test public void testUnnamedSection() throws Exception
{
    IniParser parser = new IniParser();
    IniHandler handler = EasyMock.createMock(IniHandler.class);

    handler.startIni();
    handler.startSection(EMPTY);
    handler.handleOption(OPTION, VALUE);
    handler.endSection();
    handler.endIni();
    EasyMock.replay(handler);
    Config cfg = new Config();

    cfg.setUnnamedSection(true);
    parser.setConfig(cfg);
    parser.parse(new StringReader(CFG_UNNAMED), handler);
    EasyMock.verify(handler);
}
 
Example 3
Project: dubbox-hystrix   File: ContextFilterTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSetContext() {
    invocation = EasyMock.createMock(Invocation.class);
    EasyMock.expect(invocation.getMethodName()).andReturn("$enumlength").anyTimes();
    EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Enum.class }).anyTimes();
    EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
    EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes();
    EasyMock.replay(invocation);
    invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
    RpcResult result = new RpcResult();
    result.setValue("High");
    EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
    EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
    EasyMock.replay(invoker);
    contextFilter.invoke(invoker, invocation);
    assertNull(RpcContext.getContext().getInvoker());
}
 
Example 4
Project: java_mooc_fi   File: AccountsTest.java   View source code 6 votes vote down vote up
@Test
public void testaa() throws Exception {
    Account tiliMock = createMock(Account.class);

    expectNew(Account.class, EasyMock.anyString(), EasyMock.eq(100.0)).andReturn(tiliMock);

    tiliMock.deposit(20.0);
    replay(tiliMock, Account.class);

    try {
        Accounts.main(new String[0]);
        verify(tiliMock, Account.class);

    } catch (Throwable t) {
        String virhe = t.getMessage();
        if (virhe.contains("deposit")) {
            fail("create an account and do a deposit of 20");
        } else if (virhe.contains("constructor")) {
            fail("remember to create account with initial balance of 100.0, "
                    + "the value should be in the constructor parameter");
        }
        fail("Something unexpected happened:\n" + virhe);
    }
}
 
Example 5
Project: athena   File: OspfInterfaceImplTest.java   View source code 6 votes vote down vote up
/**
 * Utility for test method.
 */
private OspfInterfaceImpl createOspfInterface1() throws UnknownHostException {
    ospfInterface = new OspfInterfaceImpl();
    OspfAreaImpl ospfArea = new OspfAreaImpl();
    OspfInterfaceChannelHandler ospfInterfaceChannelHandler = EasyMock.createMock(
            OspfInterfaceChannelHandler.class);
    ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("10.226.165.164"),
                              Ip4Address.valueOf("1.1.1.1"), 2,
                              topologyForDeviceAndLink);
    ospfNbr.setState(OspfNeighborState.FULL);
    ospfNbr.setNeighborId(Ip4Address.valueOf("10.226.165.100"));
    ospfInterface = new OspfInterfaceImpl();
    ospfInterface.setIpAddress(Ip4Address.valueOf("10.226.165.164"));
    ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
    ospfInterface.setBdr(Ip4Address.valueOf("111.111.111.111"));
    ospfInterface.setDr(Ip4Address.valueOf("111.111.111.111"));
    ospfInterface.setHelloIntervalTime(20);
    ospfInterface.setInterfaceType(2);
    ospfInterface.setReTransmitInterval(2000);
    ospfInterface.setMtu(6500);
    ospfInterface.setRouterDeadIntervalTime(1000);
    ospfInterface.setRouterPriority(1);
    ospfInterface.setInterfaceType(1);
    ospfInterface.addNeighbouringRouter(ospfNbr);
    return ospfInterface;
}
 
Example 6
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSourceTaskTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void expectOffsetFlush(boolean succeed) throws Exception {
    EasyMock.expect(offsetWriter.beginFlush()).andReturn(true);
    Future<Void> flushFuture = PowerMock.createMock(Future.class);
    EasyMock.expect(offsetWriter.doFlush(EasyMock.anyObject(Callback.class))).andReturn(flushFuture);
    // Should throw for failure
    IExpectationSetters<Void> futureGetExpect = EasyMock.expect(
            flushFuture.get(EasyMock.anyLong(), EasyMock.anyObject(TimeUnit.class)));
    if (succeed) {
        sourceTask.commit();
        EasyMock.expectLastCall();
        futureGetExpect.andReturn(null);
    } else {
        futureGetExpect.andThrow(new TimeoutException());
        offsetWriter.cancelFlush();
        PowerMock.expectLastCall();
    }
}
 
Example 7
Project: uPortal-start   File: PersonDirAuthenticationHandlerTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidSHA256Password() throws Exception {
    final UserPasswordDao userPasswordDao = EasyMock.createMock(UserPasswordDao.class);
    EasyMock.expect(userPasswordDao.getPasswordHash("student"))
            .andReturn("(SHA256)KwAQC001SoPq/CjHMLSz2o0aAqx7WrKeRFgWOeM2GEyLXGZd+1/XkA==");

    final PersonDirAuthenticationHandler authenticationHandler =
            new PersonDirAuthenticationHandler();
    authenticationHandler.setUserPasswordDao(userPasswordDao);

    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();
    credentials.setUsername("student");
    credentials.setPassword("student");

    EasyMock.replay(userPasswordDao);

    final boolean auth =
            authenticationHandler.authenticateUsernamePasswordInternal(credentials);

    EasyMock.verify(userPasswordDao);

    assertFalse(auth);
}
 
Example 8
Project: athena   File: OspfNbrImplTest.java   View source code 6 votes vote down vote up
/**
 * Tests negotiationDone() method.
 */
@Test
public void testNegotiationDone() throws Exception {

    ospfLsaList = new ArrayList();
    RouterLsa routerLsa = new RouterLsa();
    routerLsa.setLsType(OspfLsaType.ROUTER.value());
    ospfLsaList.add(routerLsa);
    DdPacket ddPacket = new DdPacket();
    ddPacket.setIsOpaqueCapable(true);
    ospfMessage = ddPacket;
    ospfNbr.setState(OspfNeighborState.EXSTART);
    ospfNbr.setIsOpaqueCapable(true);
    channel = null;
    channel = EasyMock.createMock(Channel.class);
    ospfNbr.negotiationDone(ospfMessage, true, ospfLsaList, channel);
    channel1 = EasyMock.createMock(Channel.class);
    ospfNbr.negotiationDone(ospfMessage, false, ospfLsaList, channel1);
    assertThat(ospfNbr, is(notNullValue()));
}
 
Example 9
Project: uPortal-start   File: PersonDirAuthenticationHandlerTest.java   View source code 6 votes vote down vote up
@Test
public void testNullPassword() throws Exception {
    final UserPasswordDao userPasswordDao = EasyMock.createMock(UserPasswordDao.class);
    EasyMock.expect(userPasswordDao.getPasswordHash("admin")).andReturn(null);

    final PersonDirAuthenticationHandler authenticationHandler =
            new PersonDirAuthenticationHandler();
    authenticationHandler.setUserPasswordDao(userPasswordDao);

    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();
    credentials.setUsername("admin");
    credentials.setPassword("admin");

    EasyMock.replay(userPasswordDao);

    final boolean auth =
            authenticationHandler.authenticateUsernamePasswordInternal(credentials);

    EasyMock.verify(userPasswordDao);

    assertFalse(auth);
}
 
Example 10
Project: dubbox-hystrix   File: EchoFilterTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testEcho() {
    Invocation invocation = EasyMock.createMock(Invocation.class);
    EasyMock.expect(invocation.getMethodName()).andReturn("$echo").anyTimes();
    EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Enum.class }).anyTimes();
    EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
    EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes();
    EasyMock.replay(invocation);
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
    RpcResult result = new RpcResult();
    result.setValue("High");
    EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
    EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
    EasyMock.replay(invoker);
    Result filterResult = echoFilter.invoke(invoker, invocation);
    assertEquals("hello", filterResult.getValue());
}
 
Example 11
Project: dubbox-hystrix   File: ListTelnetHandlerTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testListDetail() throws RemotingException {
    int port = NetUtils.getAvailablePort();
    mockInvoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(mockInvoker.getInterface()).andReturn(DemoService.class).anyTimes();
    EasyMock.expect(mockInvoker.getUrl()).andReturn(URL.valueOf("dubbo://127.0.0.1:"+port+"/demo")).anyTimes();
    EasyMock.expect(mockInvoker.invoke((Invocation) EasyMock.anyObject())).andReturn(new RpcResult("ok")).anyTimes();
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn(null).anyTimes();
    EasyMock.replay(mockChannel, mockInvoker);
    DubboProtocol.getDubboProtocol().export(mockInvoker);
    String result = list.telnet(mockChannel, "-l");
    assertEquals("com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService -> dubbo://127.0.0.1:"+port+"/demo", result);
    EasyMock.reset(mockChannel);
}
 
Example 12
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskThreadedTest.java   View source code 6 votes vote down vote up
private void expectPollInitialAssignment() throws Exception {
    final List<TopicPartition> partitions = Arrays.asList(TOPIC_PARTITION, TOPIC_PARTITION2, TOPIC_PARTITION3);

    sinkTask.open(partitions);
    EasyMock.expectLastCall();

    EasyMock.expect(consumer.poll(EasyMock.anyLong())).andAnswer(new IAnswer<ConsumerRecords<byte[], byte[]>>() {
        @Override
        public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
            rebalanceListener.getValue().onPartitionsAssigned(partitions);
            return ConsumerRecords.empty();
        }
    });
    EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(FIRST_OFFSET);
    EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(FIRST_OFFSET);
    EasyMock.expect(consumer.position(TOPIC_PARTITION3)).andReturn(FIRST_OFFSET);

    sinkTask.put(Collections.<SinkRecord>emptyList());
    EasyMock.expectLastCall();
}
 
Example 13
Project: athena   File: OspfInterfaceImplTest.java   View source code 6 votes vote down vote up
/**
 * Tests processHelloMessage() method.
 */
@Test
public void testProcessHelloMessage() throws Exception {
    ospfInterface.setIpAddress(Ip4Address.valueOf("11.11.11.11"));
    ospfInterface.setInterfaceType(1);
    ospfInterface.setIpNetworkMask(Ip4Address.valueOf("244.244.244.244"));
    ospfInterface.setHelloIntervalTime(10);
    ospfInterface.setRouterDeadIntervalTime(10);
    ospfArea.setAreaId(Ip4Address.valueOf("12.12.12.12"));
    channelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class);
    OspfMessage message;
    helloPacket = new HelloPacket();
    helloPacket.setSourceIp(Ip4Address.valueOf("1.1.1.1"));
    helloPacket.setOspfVer(2);
    helloPacket.setAreaId(Ip4Address.valueOf("12.12.12.12"));
    helloPacket.setNetworkMask(Ip4Address.valueOf("244.244.244.244"));
    helloPacket.setHelloInterval(10);
    helloPacket.setRouterDeadInterval(10);
    helloPacket.setDr(Ip4Address.valueOf("10.10.10.10"));
    helloPacket.setBdr(Ip4Address.valueOf("11.11.11.11"));
    helloPacket.setRouterId(Ip4Address.valueOf("111.111.111.111"));
    message = helloPacket;
    ospfInterface.processHelloMessage(message, channelHandlerContext);
    assertThat(ospfInterfaceChannelHandler, is(notNullValue()));
}
 
Example 14
Project: dubbox-hystrix   File: InvokerTelnetHandlerTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInvokeDefaultSService() throws RemotingException {
    mockInvoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(mockInvoker.getInterface()).andReturn(DemoService.class).anyTimes();
    EasyMock.expect(mockInvoker.getUrl()).andReturn(URL.valueOf("dubbo://127.0.0.1:20883/demo")).anyTimes();
    EasyMock.expect(mockInvoker.invoke((Invocation) EasyMock.anyObject())).andReturn(new RpcResult("ok")).anyTimes();
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn("com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService").anyTimes();
    EasyMock.expect(mockChannel.getLocalAddress()).andReturn(NetUtils.toAddress("127.0.0.1:5555")).anyTimes();
    EasyMock.expect(mockChannel.getRemoteAddress()).andReturn(NetUtils.toAddress("127.0.0.1:20883")).anyTimes();
    EasyMock.replay(mockChannel, mockInvoker);
    DubboProtocol.getDubboProtocol().export(mockInvoker);
    String result = invoke.telnet(mockChannel, "DemoService.echo(\"ok\")");
    assertTrue(result.contains("Use default service com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService.\r\n\"ok\"\r\n"));
    EasyMock.reset(mockChannel, mockInvoker);
}
 
Example 15
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskTest.java   View source code 6 votes vote down vote up
private void expectConsumerPoll(final int numMessages, final long timestamp, final TimestampType timestampType) {
    EasyMock.expect(consumer.poll(EasyMock.anyLong())).andAnswer(
            new IAnswer<ConsumerRecords<byte[], byte[]>>() {
                @Override
                public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
                    List<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>();
                    for (int i = 0; i < numMessages; i++)
                        records.add(new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + recordsReturned + i, timestamp, timestampType, 0L, 0, 0, RAW_KEY, RAW_VALUE));
                    recordsReturned += numMessages;
                    return new ConsumerRecords<>(
                            numMessages > 0 ?
                                    Collections.singletonMap(new TopicPartition(TOPIC, PARTITION), records) :
                                    Collections.<TopicPartition, List<ConsumerRecord<byte[], byte[]>>>emptyMap()
                    );
                }
            });
}
 
Example 16
Project: athena   File: OspfInterfaceImplTest.java   View source code 6 votes vote down vote up
/**
 * Utility for test method.
 */
private OspfInterfaceImpl createOspfInterface() throws UnknownHostException {
    ospfInterface = new OspfInterfaceImpl();
    OspfAreaImpl ospfArea = new OspfAreaImpl();
    OspfInterfaceChannelHandler ospfInterfaceChannelHandler = EasyMock.createMock(
            OspfInterfaceChannelHandler.class);
    ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("10.226.165.164"),
                              Ip4Address.valueOf("1.1.1.1"), 2,
                              topologyForDeviceAndLink);
    ospfNbr.setState(OspfNeighborState.EXSTART);
    ospfNbr.setNeighborId(Ip4Address.valueOf("10.226.165.100"));
    this.ospfInterface = new OspfInterfaceImpl();
    this.ospfInterface.setIpAddress(Ip4Address.valueOf("10.226.165.164"));
    this.ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
    this.ospfInterface.setBdr(Ip4Address.valueOf("111.111.111.111"));
    this.ospfInterface.setDr(Ip4Address.valueOf("111.111.111.111"));
    this.ospfInterface.setHelloIntervalTime(20);
    this.ospfInterface.setInterfaceType(2);
    this.ospfInterface.setReTransmitInterval(2000);
    this.ospfInterface.setMtu(6500);
    this.ospfInterface.setRouterDeadIntervalTime(1000);
    this.ospfInterface.setRouterPriority(1);
    this.ospfInterface.setInterfaceType(1);
    this.ospfInterface.addNeighbouringRouter(ospfNbr);
    return this.ospfInterface;
}
 
Example 17
Project: EatDubbo   File: ForkingClusterInvokerTest.java   View source code 6 votes vote down vote up
private void resetInvokerToException() {
    EasyMock.reset(invoker1);
    EasyMock.expect(invoker1.invoke(invocation)).andThrow(new RuntimeException()).anyTimes();
    EasyMock.expect(invoker1.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker1.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker1.getInterface()).andReturn(ForkingClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker1);
    EasyMock.reset(invoker2);
    EasyMock.expect(invoker2.invoke(invocation)).andThrow(new RuntimeException()).anyTimes();
    EasyMock.expect(invoker2.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker2.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker2.getInterface()).andReturn(ForkingClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker2);
    EasyMock.reset(invoker3);
    EasyMock.expect(invoker3.invoke(invocation)).andThrow(new RuntimeException()).anyTimes();
    EasyMock.expect(invoker3.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker3.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker3.getInterface()).andReturn(ForkingClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker3);
}
 
Example 18
Project: EatDubbo   File: ForkingClusterInvokerTest.java   View source code 6 votes vote down vote up
private void resetInvokerToNoException() {
    EasyMock.reset(invoker1);
    EasyMock.expect(invoker1.invoke(invocation)).andReturn(result).anyTimes();
    EasyMock.expect(invoker1.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker1.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker1.getInterface()).andReturn(ForkingClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker1);
    EasyMock.reset(invoker2);
    EasyMock.expect(invoker2.invoke(invocation)).andReturn(result).anyTimes();
    EasyMock.expect(invoker2.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker2.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker2.getInterface()).andReturn(ForkingClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker2);
    EasyMock.reset(invoker3);
    EasyMock.expect(invoker3.invoke(invocation)).andReturn(result).anyTimes();
    EasyMock.expect(invoker3.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker3.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker3.getInterface()).andReturn(ForkingClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker3);
}
 
Example 19
Project: dubbox-hystrix   File: InvokerTelnetHandlerTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInvokeAutoFindMethod() throws RemotingException {
    mockInvoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(mockInvoker.getInterface()).andReturn(DemoService.class).anyTimes();
    EasyMock.expect(mockInvoker.getUrl()).andReturn(URL.valueOf("dubbo://127.0.0.1:20883/demo")).anyTimes();
    EasyMock.expect(mockInvoker.invoke((Invocation) EasyMock.anyObject())).andReturn(new RpcResult("ok")).anyTimes();
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn(null).anyTimes();
    EasyMock.expect(mockChannel.getLocalAddress()).andReturn(NetUtils.toAddress("127.0.0.1:5555")).anyTimes();
    EasyMock.expect(mockChannel.getRemoteAddress()).andReturn(NetUtils.toAddress("127.0.0.1:20883")).anyTimes();
    EasyMock.replay(mockChannel, mockInvoker);
    DubboProtocol.getDubboProtocol().export(mockInvoker);
    String result = invoke.telnet(mockChannel, "echo(\"ok\")");
    assertTrue(result.contains("ok"));
    EasyMock.reset(mockChannel, mockInvoker);
}
 
Example 20
Project: kafka-0.11.0.0-src-with-comment   File: DistributedHerderTest.java   View source code 6 votes vote down vote up
@Test
public void testJoinAssignment() throws Exception {
    // Join group and get assignment
    EasyMock.expect(member.memberId()).andStubReturn("member");
    EasyMock.expect(worker.getPlugins()).andReturn(plugins);
    expectRebalance(1, Arrays.asList(CONN1), Arrays.asList(TASK1));
    expectPostRebalanceCatchup(SNAPSHOT);
    worker.startConnector(EasyMock.eq(CONN1), EasyMock.<Map<String, String>>anyObject(), EasyMock.<ConnectorContext>anyObject(),
            EasyMock.eq(herder), EasyMock.eq(TargetState.STARTED));
    PowerMock.expectLastCall().andReturn(true);
    EasyMock.expect(worker.isRunning(CONN1)).andReturn(true);

    EasyMock.expect(worker.connectorTaskConfigs(CONN1, MAX_TASKS, null)).andReturn(TASK_CONFIGS);
    worker.startTask(EasyMock.eq(TASK1), EasyMock.<Map<String, String>>anyObject(), EasyMock.<Map<String, String>>anyObject(),
            EasyMock.eq(herder), EasyMock.eq(TargetState.STARTED));
    PowerMock.expectLastCall().andReturn(true);
    member.poll(EasyMock.anyInt());
    PowerMock.expectLastCall();

    PowerMock.replayAll();

    herder.tick();

    PowerMock.verifyAll();
}
 
Example 21
Project: kafka-0.11.0.0-src-with-comment   File: KafkaStatusBackingStoreTest.java   View source code 6 votes vote down vote up
@Test
public void putSafeWithNoPreviousValueIsPropagated() {
    final Converter converter = mock(Converter.class);
    final KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
    final KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

    final byte[] value = new byte[0];

    final Capture<Struct> statusValueStruct = newCapture();
    converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), capture(statusValueStruct));
    EasyMock.expectLastCall().andReturn(value);

    kafkaBasedLog.send(eq("status-connector-" + CONNECTOR), eq(value), anyObject(Callback.class));
    expectLastCall();

    replayAll();

    final ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.FAILED, WORKER_ID, 0);
    store.putSafe(status);

    verifyAll();

    assertEquals(status.state().toString(), statusValueStruct.getValue().get(KafkaStatusBackingStore.STATE_KEY_NAME));
    assertEquals(status.workerId(), statusValueStruct.getValue().get(KafkaStatusBackingStore.WORKER_ID_KEY_NAME));
    assertEquals(status.generation(), statusValueStruct.getValue().get(KafkaStatusBackingStore.GENERATION_KEY_NAME));
}
 
Example 22
Project: dubbocloud   File: ExceptionFilterTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRpcException() {
    Logger logger = EasyMock.createMock(Logger.class);
    RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234);
    RpcException exception = new RpcException("TestRpcException");
    logger.error(EasyMock.eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), EasyMock.eq(exception));
    ExceptionFilter exceptionFilter = new ExceptionFilter(logger);
    RpcInvocation invocation = new RpcInvocation("sayHello", new Class<?>[]{String.class}, new Object[]{"world"});
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class);
    EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception);
    
    EasyMock.replay(logger, invoker);
    
    try {
        exceptionFilter.invoke(invoker, invocation);
    } catch (RpcException e) {
        assertEquals("TestRpcException", e.getMessage());
    }
    EasyMock.verify(logger, invoker);
    RpcContext.removeContext();
}
 
Example 23
Project: EatDubbo   File: InvokerTelnetHandlerTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInvokeAutoFindMethod() throws RemotingException {
    mockInvoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(mockInvoker.getInterface()).andReturn(DemoService.class).anyTimes();
    EasyMock.expect(mockInvoker.getUrl()).andReturn(URL.valueOf("dubbo://127.0.0.1:20883/demo")).anyTimes();
    EasyMock.expect(mockInvoker.invoke((Invocation) EasyMock.anyObject())).andReturn(new RpcResult("ok")).anyTimes();
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn(null).anyTimes();
    EasyMock.expect(mockChannel.getLocalAddress()).andReturn(NetUtils.toAddress("127.0.0.1:5555")).anyTimes();
    EasyMock.expect(mockChannel.getRemoteAddress()).andReturn(NetUtils.toAddress("127.0.0.1:20883")).anyTimes();
    EasyMock.replay(mockChannel, mockInvoker);
    DubboProtocol.getDubboProtocol().export(mockInvoker);
    String result = invoke.telnet(mockChannel, "echo(\"ok\")");
    assertTrue(result.contains("ok"));
    EasyMock.reset(mockChannel, mockInvoker);
}
 
Example 24
Project: athena   File: OspfNbrImplTest.java   View source code 6 votes vote down vote up
/**
 * Utility for test method.
 */
private OspfInterfaceImpl createOspfInterface() throws UnknownHostException {
    ospfInterface = new OspfInterfaceImpl();
    OspfAreaImpl ospfArea = new OspfAreaImpl();
    OspfInterfaceChannelHandler ospfInterfaceChannelHandler = EasyMock.createMock(
            OspfInterfaceChannelHandler.class);
    ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("10.226.165.164"),
                              Ip4Address.valueOf("1.1.1.1"), 2,
                              topologyForDeviceAndLink);
    ospfNbr.setState(OspfNeighborState.EXSTART);
    ospfNbr.setNeighborId(Ip4Address.valueOf("10.226.165.100"));
    this.ospfInterface = new OspfInterfaceImpl();
    this.ospfInterface.setIpAddress(Ip4Address.valueOf("10.226.165.164"));
    this.ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
    this.ospfInterface.setBdr(Ip4Address.valueOf("111.111.111.111"));
    this.ospfInterface.setDr(Ip4Address.valueOf("111.111.111.111"));
    this.ospfInterface.setHelloIntervalTime(20);
    this.ospfInterface.setInterfaceType(2);
    this.ospfInterface.setReTransmitInterval(2000);
    this.ospfInterface.setMtu(6500);
    this.ospfInterface.setRouterDeadIntervalTime(1000);
    this.ospfInterface.setRouterPriority(1);
    this.ospfInterface.setInterfaceType(1);
    this.ospfInterface.addNeighbouringRouter(ospfNbr);
    return this.ospfInterface;
}
 
Example 25
Project: dubbox-hystrix   File: CompatibleFilterFilterTest.java   View source code 6 votes vote down vote up
@Test
public void testInvokerJsonPojoSerialization() {
    invocation = EasyMock.createMock(Invocation.class);
    EasyMock.expect(invocation.getMethodName()).andReturn("enumlength").anyTimes();
    EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Type[].class }).anyTimes();
    EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
    EasyMock.replay(invocation);
    invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
    RpcResult result = new RpcResult();
    result.setValue("High");
    EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&serialization=json");
    EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
    EasyMock.replay(invoker);
    Result filterResult = compatibleFilter.invoke(invoker, invocation);
    assertEquals(Type.High, filterResult.getValue());
}
 
Example 26
Project: EatDubbo   File: ListTelnetHandlerTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testListDefault() throws RemotingException {
    mockInvoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(mockInvoker.getInterface()).andReturn(DemoService.class).anyTimes();
    EasyMock.expect(mockInvoker.getUrl()).andReturn(URL.valueOf("dubbo://127.0.0.1:20885/demo")).anyTimes();
    EasyMock.expect(mockInvoker.invoke((Invocation) EasyMock.anyObject())).andReturn(new RpcResult("ok")).anyTimes();
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn("com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService").anyTimes();
    EasyMock.replay(mockChannel, mockInvoker);
    DubboProtocol.getDubboProtocol().export(mockInvoker);
    String result = list.telnet(mockChannel, "");
    assertEquals("Use default service com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService.\r\n\r\n"
                 + methodsName, result);
    EasyMock.reset(mockChannel);
}
 
Example 27
Project: creacoinj   File: PaymentChannelClientTest.java   View source code 6 votes vote down vote up
@Test
public void shouldSendTimeWindowInClientVersion() throws Exception {
    final long timeWindow = 4000;
    KeyParameter userKey = null;
    PaymentChannelClient dut =
            new PaymentChannelClient(wallet, ecKey, maxValue, serverHash, userKey, new PaymentChannelClient.DefaultClientChannelProperties() {
                @Override
                public long timeWindow() {
                    return timeWindow;
                }

                @Override
                public PaymentChannelClient.VersionSelector versionSelector() {
                    return clientChannelProperties.versionSelector();
                }
            }, connection);
    connection.sendToServer(capture(clientVersionCapture));
    EasyMock.expect(wallet.getExtensions()).andReturn(new HashMap<String, WalletExtension>());
    replay(connection, wallet);
    dut.connectionOpen();
    assertClientVersion(4000);
}
 
Example 28
Project: dubbo2   File: ContextFilterTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSetContext() {
    invocation = EasyMock.createMock(Invocation.class);
    EasyMock.expect(invocation.getMethodName()).andReturn("$enumlength").anyTimes();
    EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Enum.class }).anyTimes();
    EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
    EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes();
    EasyMock.replay(invocation);
    invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
    RpcResult result = new RpcResult();
    result.setValue("High");
    EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
    EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
    EasyMock.replay(invoker);
    contextFilter.invoke(invoker, invocation);
    assertNull(RpcContext.getContext().getInvoker());
}
 
Example 29
Project: ats-framework   File: Test_FTPClient.java   View source code 6 votes vote down vote up
@Test
public void testChangeModeBinary() throws Exception {

    expectNew(org.apache.commons.net.ftp.FTPClient.class).andReturn(mockFtp);

    mockFtp.setConnectTimeout(DEFAULT_TIMEOUT);
    mockFtp.connect(HOSTNAME, PORT_NUMBER);
    mockFtp.setAutodetectUTF8(false);
    EasyMock.expectLastCall().once();
    expect(mockFtp.login(USERNAME, PASSWORD)).andReturn(true);
    mockFtp.enterLocalPassiveMode();
    expect(mockFtp.setFileType(org.apache.commons.net.ftp.FTPClient.ASCII_FILE_TYPE)).andReturn(true);

    expect(mockFtp.isConnected()).andReturn(true);
    expect(mockFtp.setFileType(org.apache.commons.net.ftp.FTPClient.BINARY_FILE_TYPE)).andReturn(true);

    replayAll();

    testObject.setTransferMode(TransferMode.ASCII);
    testObject.connect(HOSTNAME, USERNAME, PASSWORD);
    testObject.setTransferMode(TransferMode.BINARY);

    verifyAll();
}
 
Example 30
Project: EatDubbo   File: CompatibleFilterFilterTest.java   View source code 6 votes vote down vote up
@Test
public void testInvokerNonJsonPojoSerialization() {
    invocation = EasyMock.createMock(Invocation.class);
    EasyMock.expect(invocation.getMethodName()).andReturn("echo").anyTimes();
    EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { String.class }).anyTimes();
    EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
    EasyMock.replay(invocation);
    invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
    RpcResult result = new RpcResult();
    result.setValue("hello");
    EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
    EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
    EasyMock.replay(invoker);
    Result filterResult = compatibleFilter.invoke(invoker, invocation);
    assertEquals("hello", filterResult.getValue());
}
 
Example 31
Project: dubbo2   File: FailfastClusterInvokerTest.java   View source code 6 votes vote down vote up
@Test()
public void testNoInvoke() {
    dic = EasyMock.createMock(Directory.class);
    
    EasyMock.expect(dic.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(dic.list(invocation)).andReturn(null).anyTimes();
    EasyMock.expect(dic.getInterface()).andReturn(FailfastClusterInvokerTest.class).anyTimes();
    
    invocation.setMethodName("method1");
    EasyMock.replay(dic);
    
    invokers.add(invoker1);
    
    resetInvoker1ToNoException();
    
    FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<FailfastClusterInvokerTest>(dic);
    try {
        invoker.invoke(invocation);
        fail();
    } catch (RpcException expected) {
        assertFalse(expected.getCause() instanceof RpcException);
    }
}
 
Example 32
Project: fresco_floodlight   File: TopologyInstanceTest.java   View source code 6 votes vote down vote up
@Before 
public void SetUp() throws Exception {
    fmc = new FloodlightModuleContext();
    linkDiscovery = EasyMock.createMock(ILinkDiscoveryService.class);
    mockFloodlightProvider = new MockFloodlightProvider();
    fmc.addService(IFloodlightProviderService.class, mockFloodlightProvider);
    fmc.addService(IOFSwitchService.class, new MockSwitchManager());
    fmc.addService(ILinkDiscoveryService.class, linkDiscovery);
    fmc.addService(IDebugCounterService.class, new MockDebugCounterService());
    fmc.addService(IDebugEventService.class, new MockDebugEventService());
    MockThreadPoolService tp = new MockThreadPoolService();
    topologyManager = new TopologyManager();
    fmc.addService(IThreadPoolService.class, tp);
    topologyManager.init(fmc);
    tp.init(fmc);
    tp.startUp(fmc);
}
 
Example 33
Project: cruise-control   File: BrokerFailureDetectorTest.java   View source code 5 votes vote down vote up
private BrokerFailureDetector createBrokerFailureDetector(Queue<Anomaly> anomalies, Time time) {
  LoadMonitor mockLoadMonitor = EasyMock.mock(LoadMonitor.class);
  EasyMock.expect(mockLoadMonitor.brokersWithPartitions(anyLong())).andAnswer(() -> new HashSet<>(Arrays.asList(0, 1))).anyTimes();
  EasyMock.replay(mockLoadMonitor);
  Properties props = CruiseControlUnitTestUtils.getCruiseControlProperties();
  props.setProperty(KafkaCruiseControlConfig.ZOOKEEPER_CONNECT_CONFIG, zookeeper().getConnectionString());
  KafkaCruiseControlConfig kafkaCruiseControlConfig = new KafkaCruiseControlConfig(props);
  return new BrokerFailureDetector(kafkaCruiseControlConfig,
                                   mockLoadMonitor,
                                   anomalies,
                                   time);
}
 
Example 34
Project: dubbox-hystrix   File: FailfastClusterInvokerTest.java   View source code 5 votes vote down vote up
private void resetInvoker1ToException(){
    EasyMock.reset(invoker1);
    EasyMock.expect(invoker1.invoke(invocation)).andThrow(new RuntimeException()).anyTimes();
    EasyMock.expect(invoker1.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker1.getInterface()).andReturn(FailfastClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker1);
}
 
Example 35
Project: dubbocloud   File: InvokerTelnetHandlerTest.java   View source code 5 votes vote down vote up
@Test
public void testInvaildMessage() throws RemotingException {
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn(null).anyTimes();
    EasyMock.replay(mockChannel);
    String result = invoke.telnet(mockChannel, "(");
    assertEquals("Invalid parameters, format: service.method(args)", result);
    EasyMock.reset(mockChannel);
}
 
Example 36
Project: kafka-0.11.0.0-src-with-comment   File: DistributedHerderTest.java   View source code 5 votes vote down vote up
@Test
public void testRestartUnknownTask() throws Exception {
    // get the initial assignment
    EasyMock.expect(member.memberId()).andStubReturn("member");
    expectRebalance(1, Collections.<String>emptyList(), Collections.<ConnectorTaskId>emptyList());
    expectPostRebalanceCatchup(SNAPSHOT);
    member.poll(EasyMock.anyInt());
    PowerMock.expectLastCall();

    member.wakeup();
    PowerMock.expectLastCall();
    member.ensureActive();
    PowerMock.expectLastCall();
    member.poll(EasyMock.anyInt());
    PowerMock.expectLastCall();

    PowerMock.replayAll();

    FutureCallback<Void> callback = new FutureCallback<>();
    herder.tick();
    herder.restartTask(new ConnectorTaskId("blah", 0), callback);
    herder.tick();

    try {
        callback.get(1000L, TimeUnit.MILLISECONDS);
        fail("Expected NotLeaderException to be raised");
    } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof NotFoundException);
    }

    PowerMock.verifyAll();
}
 
Example 37
Project: dubbox-hystrix   File: FailbackClusterInvokerTest.java   View source code 5 votes vote down vote up
/**
 * @throws java.lang.Exception
 */

@Before
public void setUp() throws Exception {

    dic = EasyMock.createMock(Directory.class);
    EasyMock.expect(dic.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(dic.list(invocation)).andReturn(invokers).anyTimes();
    EasyMock.expect(dic.getInterface()).andReturn(FailbackClusterInvokerTest.class).anyTimes();

    invocation.setMethodName("method1");
    EasyMock.replay(dic);

    invokers.add(invoker);
}
 
Example 38
Project: ms-gs-plugins   File: BoundsUpdateTransactionListenerTest.java   View source code 5 votes vote down vote up
void mockLayerGroupList(List<LayerGroupInfo> groups) {
    Capture<Filter> filterCapture = new Capture<>();
    EasyMock.expect(catalog.list(EasyMock.eq(LayerGroupInfo.class), EasyMock.capture(filterCapture)))
        .andStubAnswer(()->{
            List<LayerGroupInfo> matchingGroups = groups.stream()
                .filter(x->filterCapture.getValue().evaluate(x))
                .collect(Collectors.toList());
            return new CloseableIteratorAdapter<LayerGroupInfo>(
                matchingGroups
                    .iterator()
                    );
            });
}
 
Example 39
Project: gemini.blueprint   File: OsgiServiceAnnotationTest.java   View source code 5 votes vote down vote up
protected void setUp() throws Exception {
	super.setUp();
	processor = new ServiceReferenceInjectionBeanPostProcessor();
	context = new MockBundleContext();
	processor.setBundleContext(context);
	processor.setBeanClassLoader(getClass().getClassLoader());
	BeanFactory factory = EasyMock.createMock(BeanFactory.class);
	processor.setBeanFactory(factory);
}
 
Example 40
Project: gswagon-maven-plugin   File: GSWagonTest.java   View source code 5 votes vote down vote up
@Test
public void testPut() throws Exception
{
  expect(connectionPOJO.storage.create(EasyMock.anyObject(), EasyMock.<InputStream>anyObject()))
      .andReturn(null)
      .once();
  replay(connectionPOJO.storage);
  gsWagon.swapAndCloseConnection(connectionPOJO);
  gsWagon.put(temporaryFolder.newFile(), "foo");
  verify(connectionPOJO.storage);
}