Java Code Examples for org.jmock.Mockery#mock()

The following examples show how to use org.jmock.Mockery#mock() . 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: ChannelInitializerTest.java    From nanofix with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    mockery = new Mockery();
    mockery.setImposteriser(ClassImposteriser.INSTANCE);
    transport = mockery.mock(Transport.class);
    byteChannelReader = mockery.mock(ByteChannelReader.class);
    outboundMessageHandler = mockery.mock(OutboundMessageHandler.class);
    writableByteChannel = mockery.mock(WritableByteChannel.class);
    readableByteChannel = mockery.mock(ReadableByteChannel.class);

    mockery.checking(new Expectations()
    {
        {
            ignoring(writableByteChannel);
        }
    });
}
 
Example 2
Source File: FileMoverTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public void test_moving_file_to_server() throws IOException {
    Mockery mockContext = new Mockery();
    final FileMoverStrategy mockedFileMoverStrategy = mockContext.mock(FileMoverStrategy.class);
    final WctDepositParameter depositParameter = new WctDepositParameter();

    createExpectations(mockContext, mockedFileMoverStrategy, depositParameter);

    List<ArchiveFile> files = populateListWithOneArchiveFile();

    FileMover fileMover = new FileMoverImpl(mockedFileMoverStrategy);
    MetsDocument metsDoc = new MetsDocument("mets.xml", "the xml");
    fileMover.move(metsDoc, files, depositParameter);

    assertThat(metsDoc.getDepositDirectoryName(), containsString("deposit"));

    mockContext.assertIsSatisfied();
}
 
Example 3
Source File: FtpFileMoverTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void test_calling_create_And_Change_To_Directory_when_not_connected() throws IOException {
    Mockery mockContext = constructMockContext();

    final FTPClient mockedFtpClient = mockContext.mock(FTPClient.class);
    final FtpClientFactory mockedFactory = mockContext.mock(FtpClientFactory.class);

    mockContext.checking(new Expectations() {
        {
            one(mockedFactory).createInstance();
            will(returnValue(mockedFtpClient));
        }
    });

    FtpFileMover ftpFileMover = new FtpFileMover(mockedFactory);
    ftpFileMover.createAndChangeToDirectory("directory");

    mockContext.assertIsSatisfied();
}
 
Example 4
Source File: FlexDirectionTest.java    From mini2Dx with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	Mdx.locks = new JvmLocks();

	mockery = new Mockery();
	mockery.setImposteriser(ClassImposteriser.INSTANCE);
	
	layoutState = mockery.mock(LayoutState.class);
	renderTree = mockery.mock(UiContainerRenderTree.class);
	
	mockery.checking(new Expectations() {
		{
			atLeast(1).of(layoutState).getUiContainerRenderTree();
			will(returnValue(renderTree));
			atLeast(1).of(renderTree).transferLayoutDeferred(with(any(Array.class)));
		}
	});
}
 
Example 5
Source File: RenderLayerTest.java    From mini2Dx with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	parentElement.setVisibility(Visibility.VISIBLE);
	uiElement1.setVisibility(Visibility.VISIBLE);
	uiElement2.setVisibility(Visibility.VISIBLE);
	
	mockery = new Mockery();
	mockery.setImposteriser(ClassImposteriser.INSTANCE);
	
	layoutState = mockery.mock(LayoutState.class);
	renderTree = mockery.mock(UiContainerRenderTree.class);
	
	renderLayer.add(renderNode1);
	renderLayer.add(renderNode2);

	mockery.checking(new Expectations() {
		{
			atLeast(1).of(renderTree).transferLayoutDeferred(with(any(Array.class)));
		}
	});
}
 
Example 6
Source File: AlarmMockTest.java    From androidtestdebug with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void 使用模拟IGetDate对象测试() throws InterruptedException {
	Option option = new Option();
	option.alarmTime = new Date(1, 12, 15, 16, 15, 0);
	option.repeatSetting = RepeatSetting.EveryDay;
	
	Mockery context = new Mockery();
	final IGetDate gd = context.mock(IGetDate.class);
	context.checking(new Expectations() {{
		atLeast(1).of(gd).Now(); will(returnValue(new Date(1, 12, 15, 16, 15, 0)));
	}});
	
	TestableAlarm alarm = new TestableAlarm(option, gd);
	alarm.start();
	// 休眠2秒钟,确保计时器顺利执行!
	Thread.sleep(2000);		
	alarm.stop();		
	assertEquals(1, alarm.trigerTimes);
	context.assertIsSatisfied();
}
 
Example 7
Source File: AlarmServiceTest.java    From androidtestdebug with MIT License 6 votes vote down vote up
public void testAlarm2() throws InterruptedException {
	Option option = new Option();
	option.alarmTime = new Date(1, 12, 15, 16, 15, 0);
	option.repeatSetting = RepeatSetting.EveryDay;
	
	Mockery context = new Mockery();
	final IGetDate gd = context.mock(IGetDate.class);
	context.checking(new Expectations() {{
		atLeast(1).of(gd).Now(); will(returnValue(new Date(1, 12, 15, 16, 15, 0)));
	}});
	
	TestableAlarm alarm = new TestableAlarm(option, gd, this.getContext());
	alarm.start();
	// 休眠2秒钟,确保计时器顺利执行!
	Thread.sleep(2000);		
	alarm.stop();		
	assertEquals(1, alarm.trigerTimes);
	context.assertIsSatisfied();
}
 
Example 8
Source File: AlarmServiceTest.java    From androidtestdebug with MIT License 6 votes vote down vote up
public void testAlarmService() throws InterruptedException {		
	Intent startIntent = new Intent(getContext(),AlarmService.class);
	startIntent.putExtra("TIME", 
			new Date(2111, 12, 15, 16, 15, 0).getTime());
	startService(startIntent);
	
	AlarmService service = (AlarmService)getService();
	Mockery context = new Mockery();
	final IGetDate gd = context.mock(IGetDate.class);
	context.checking(new Expectations() {{
		atLeast(1).of(gd).Now(); will(returnValue(
				new Date(2111, 12, 15, 16, 15, 0)));
	}});
	
	service.getAlarm().setIGetDate(gd);
	Thread.sleep(2000);		
	assertEquals(1, service.getAlarm().trigerTimes);
	context.assertIsSatisfied();
}
 
Example 9
Source File: DeploymentBuildAgentPodTemplateProviderTest.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
@Override
protected void setUp() throws Exception {
    super.setUp();
    m = new Mockery();
    ServerSettings serverSettings = m.mock(ServerSettings.class);
    KubeAuthStrategyProvider authStrategies = m.mock(KubeAuthStrategyProvider.class);
    myDeploymentContentProvider = m.mock(DeploymentContentProvider.class);
    final ExecutorServices executorServices = m.mock(ExecutorServices.class);
    m.checking(new Expectations(){{
        allowing(serverSettings).getServerUUID(); will(returnValue("server uuid"));
        allowing(authStrategies).get(with(UnauthorizedAccessStrategy.ID)); will(returnValue(myAuthStrategy));
        ScheduledExecutorService ses = new ScheduledThreadPoolExecutor(1);
        allowing(executorServices).getNormalExecutorService(); will(returnValue(ses));
    }});
    TempFiles tempFiles = new TempFiles();
    final ServerPaths serverPaths = new ServerPaths(tempFiles.createTempDir());
    final EventDispatcher<BuildServerListener> eventDispatcher = EventDispatcher.create(BuildServerListener.class);
    myNameGenerator = new KubePodNameGeneratorImpl(serverPaths, executorServices, eventDispatcher);
    myPodTemplateProvider = new DeploymentBuildAgentPodTemplateProvider(serverSettings, myDeploymentContentProvider);
}
 
Example 10
Source File: SSHExecProcessAdapterTest.java    From teamcity-deployer-plugin with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup() {
  myContext = new Mockery();
  myContext.setImposteriser(ClassImposteriser.INSTANCE);

  mySessionProvider = myContext.mock(SSHSessionProvider.class);
  mySession = myContext.mock(Session.class);
  myChannel = myContext.mock(ChannelExec.class);
  myLogger = myContext.mock(BuildProgressLogger.class);
  myAdapter = newAdapter(myLogger);
  commonExpectations();
}
 
Example 11
Source File: SymbolsCacheTest.java    From teamcity-symbol-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheNonEmptyEntry() {
  SymbolsCache symbolsCache = new SymbolsCache(myFixture.getEventDispatcher());
  Mockery m = new Mockery();
  AtomicInteger integer = new AtomicInteger();
  BuildMetadataEntry entry = m.mock(BuildMetadataEntry.class);
  String key = "key";

  Function<String, BuildMetadataEntry> entryFunction = s -> {
    integer.incrementAndGet();
    return entry;
  };

  m.checking(new Expectations(){{
    oneOf(entry).getBuildId();
    will(returnValue(123L));
  }});


  BuildMetadataEntry cacheEntry1 = symbolsCache.getEntry(key, entryFunction);
  BuildMetadataEntry cacheEntry2 = symbolsCache.getEntry(key, entryFunction);

  Assert.assertNotNull(cacheEntry1);
  Assert.assertEquals(cacheEntry1, cacheEntry2);
  Assert.assertEquals(cacheEntry2, entry);

  Assert.assertEquals(integer.get(), 1);
}
 
Example 12
Source File: LibgdxGraphicsTest.java    From mini2Dx with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	mockery = new Mockery();
	mockery.setImposteriser(ClassImposteriser.INSTANCE);
	fonts = mockery.mock(Fonts.class);
	gameFont = mockery.mock(GameFont.class);
	gameWrapper = mockery.mock(GameWrapper.class);
	spriteBatch = mockery.mock(LibgdxSpriteBatchWrapper.class);
	polygonSpriteBatch = mockery.mock(PolygonSpriteBatch.class);
	shapeRenderer = mockery.mock(ShapeRenderer.class);
	gdxGraphics = mockery.mock(com.badlogic.gdx.Graphics.class);

	Mdx.fonts = fonts;
	Gdx.graphics = gdxGraphics;
	
	mockery.checking(new Expectations() {
		{
			one(shapeRenderer).setAutoShapeType(true);
			one(fonts).defaultFont();
			will(returnValue(gameFont));
			one(gdxGraphics).getWidth();
			will(returnValue(800));
			one(gdxGraphics).getHeight();
			will(returnValue(600));
			one(spriteBatch).getColor();
			will(returnValue(new Color()));
		}
	});
	
	graphics = new LibgdxGraphics(gameWrapper, spriteBatch, polygonSpriteBatch, shapeRenderer);
}
 
Example 13
Source File: OutboundMessageHandlerTest.java    From nanofix with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
{
    mockery = new Mockery();
    writableByteChannel = mockery.mock(WritableByteChannel.class);
    connectionObserver = mockery.mock(ConnectionObserver.class);
    handler = new OutboundMessageHandler(connectionObserver);
    handler.initialiseOutboundChannel(writableByteChannel);
}
 
Example 14
Source File: ConfigTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testJdbcLockConfigOverride() throws Exception {

   JDBCPersistenceAdapter adapter = new JDBCPersistenceAdapter();
   Mockery context = new Mockery();
   final DataSource dataSource = context.mock(DataSource.class);
   final Connection connection = context.mock(Connection.class);
   final DatabaseMetaData metadata = context.mock(DatabaseMetaData.class);
   final ResultSet result = context.mock(ResultSet.class);
   adapter.setDataSource(dataSource);
   adapter.setCreateTablesOnStartup(false);

   context.checking(new Expectations() {{
      allowing(dataSource).getConnection();
      will(returnValue(connection));
      allowing(connection).getMetaData();
      will(returnValue(metadata));
      allowing(connection);
      allowing(metadata).getDriverName();
      will(returnValue("Microsoft_SQL_Server_2005_jdbc_driver"));
      allowing(result).next();
      will(returnValue(true));
   }});

   adapter.start();
   assertTrue("has the locker override", adapter.getLocker() instanceof TransactDatabaseLocker);
   adapter.stop();
}
 
Example 15
Source File: ConfigTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testJdbcLockConfigDefault() throws Exception {

      JDBCPersistenceAdapter adapter = new JDBCPersistenceAdapter();
      Mockery context = new Mockery();
      final DataSource dataSource = context.mock(DataSource.class);
      final Connection connection = context.mock(Connection.class);
      final DatabaseMetaData metadata = context.mock(DatabaseMetaData.class);
      final ResultSet result = context.mock(ResultSet.class);
      adapter.setDataSource(dataSource);
      adapter.setCreateTablesOnStartup(false);

      context.checking(new Expectations() {{
         allowing(dataSource).getConnection();
         will(returnValue(connection));
         allowing(connection).getMetaData();
         will(returnValue(metadata));
         allowing(connection);
         allowing(metadata).getDriverName();
         will(returnValue("Some_Unknown_driver"));
         allowing(result).next();
         will(returnValue(true));
      }});

      adapter.start();
      assertEquals("has the default locker", adapter.getLocker().getClass(), DefaultDatabaseLocker.class);
      adapter.stop();
   }
 
Example 16
Source File: DpsDepositFacadeImplTest.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void test_submission_of_wct_sip() throws Exception {

    FileInputStream fis = new FileInputStream(wctMetsPath);
    int fileSize = fis.available();
    byte[] binaryData = new byte[fileSize];
    fis.read(binaryData);
    String wctSip = new String(binaryData);

    Mockery mockContext = constructMockContext();
    final DepositWebServicesFactory depositWebServicesFactory = mockContext.mock(DepositWebServicesFactory.class);
    final DepositWebServices depositWebServices = mockContext.mock(DepositWebServices.class);
    final PdsClientFactory pdsClientFactory = mockContext.mock(PdsClientFactory.class);
    final PdsClient pdsClient = mockContext.mock(PdsClient.class);
    final DnxMapper dnxMapper = new DnxMapperImpl(new MetsWriterFactoryImpl());
    final FileMover fileMover = mockContext.mock(FileMover.class);
    final PreDepositProcessor preDepositProcessor = new ArcIndexProcessor();
    final DpsDepositFacade dpsDeposit = new DpsDepositFacadeImpl(depositWebServicesFactory, pdsClientFactory, fileMover, dnxMapper, preDepositProcessor);
    final String pdsSessionId = "pdsSessionId";
    
    populateArcFileContents();

    List<File> fileList = extractFileDetailsFrom();
    final Map<String, String> parameters = populateDepositParameter(wctSip);

    mockContext.checking(new Expectations() {
        {
            one(depositWebServicesFactory).createInstance(with(any(WctDepositParameter.class)));
            will(returnValue(depositWebServices));

            one(depositWebServices).submitDepositActivity(with(any(String.class)), with(any(String.class)), with(any(String.class)), with(any(String.class)), with(any(String.class)));
            will(returnValue(DepositResultConverterTest.buildMessage(false)));

            one(fileMover).move(with(any(MetsDocument.class)), with(any(List.class)), with(any(WctDepositParameter.class)));

            allowing(pdsClientFactory).createInstance();
            will(returnValue(pdsClient));

            allowing(pdsClient).init(with(any(String.class)), with(any(boolean.class)));

            allowing(pdsClient).login(with(any(String.class)), with(any(String.class)), with(any(String.class)));
            will(returnValue(pdsSessionId));
        }
    });
    DepositResult depositResult = dpsDeposit.deposit(parameters, fileList);
    if (depositResult.isError())
        throw new RuntimeException("Submission to DPS failed, message from DPS: " + depositResult.getMessageDesciption());
    mockContext.assertIsSatisfied();
    assertThat(depositResult.getSipId(), is(notNullValue()));
}
 
Example 17
Source File: FtpFileMoverTest.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@Test
public void test_connect() throws IOException {
    Mockery mockContext = constructMockContext();

    final FTPClient mockedFtpClient = mockContext.mock(FTPClient.class);
    final FtpClientFactory mockedFactory = mockContext.mock(FtpClientFactory.class);

    mockContext.checking(new Expectations() {
        {
            one(mockedFactory).createInstance();
            will(returnValue(mockedFtpClient));

            one(mockedFtpClient).connect(with(any(String.class)));
            one(mockedFtpClient).user(with(any(String.class)));
            will(returnValue(1));

            one(mockedFtpClient).pass(with(any(String.class)));
            one(mockedFtpClient).setFileType(FTP.BINARY_FILE_TYPE);
        }
    });

    WctDepositParameter depositParameter = new WctDepositParameter();
    FtpFileMover ftpFileMover = new FtpFileMover(mockedFactory);
    ftpFileMover.connect(depositParameter);

    mockContext.assertIsSatisfied();
}
 
Example 18
Source File: FtpFileMoverTest.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@Test
public void test_calling_create_And_Change_To_Directory() throws IOException {
    Mockery mockContext = constructMockContext();

    final FTPClient mockedFtpClient = mockContext.mock(FTPClient.class);
    final FtpClientFactory mockedFactory = mockContext.mock(FtpClientFactory.class);
    final String directoryName = "directoryName";

    mockContext.checking(new Expectations() {
        {
            one(mockedFactory).createInstance();
            will(returnValue(mockedFtpClient));

            one(mockedFtpClient).connect(with(any(String.class)));
            one(mockedFtpClient).user(with(any(String.class)));
            will(returnValue(1));

            one(mockedFtpClient).pass(with(any(String.class)));
            one(mockedFtpClient).setFileType(FTP.BINARY_FILE_TYPE);

            one(mockedFtpClient).makeDirectory(directoryName);
            will(returnValue(true));

            one(mockedFtpClient).changeWorkingDirectory(directoryName);
        }
    });

    WctDepositParameter depositParameter = new WctDepositParameter();

    FtpFileMover ftpFileMover = new FtpFileMover(mockedFactory);
    ftpFileMover.connect(depositParameter);

    ftpFileMover.createAndChangeToDirectory(directoryName);

    mockContext.assertIsSatisfied();
}
 
Example 19
Source File: CargoBuildProcessAdapterTest.java    From teamcity-deployer-plugin with Apache License 2.0 4 votes vote down vote up
@BeforeMethod
@Override
public void setUp() throws Exception {
  super.setUp();

  final File extractDir = createTempDir();
  final File cfgDir = createTempDir();

  final String fileName = "apache-tomcat-7.0.54.zip";
  final File zipDistribution = getTestResource(fileName);
  final ZipURLInstaller installer = new ZipURLInstaller(zipDistribution.toURI().toURL());

  installer.setExtractDir(extractDir.getAbsolutePath());
  installer.install();

  LocalConfiguration configuration = new Tomcat7xStandaloneLocalConfiguration(cfgDir.getAbsolutePath());
  testPort = NetworkUtil.getFreePort(DEPLOYER_DEFAULT_PORT);
  configuration.setProperty(ServletPropertySet.PORT, String.valueOf(testPort));
  configuration.setProperty(TomcatPropertySet.AJP_PORT, String.valueOf(NetworkUtil.getFreePort(8009)));
  configuration.setProperty(ServletPropertySet.USERS, "tomcat:tomcat:manager-script");

  myTomcat = (InstalledLocalContainer) new DefaultContainerFactory().createContainer(
      "tomcat7x", ContainerType.INSTALLED, configuration);

  myTomcat.setHome(installer.getHome());

  myTomcat.start();

  Mockery mockeryCtx = new Mockery();
  myContext = mockeryCtx.mock(BuildRunnerContext.class);
  final AgentRunningBuild build = mockeryCtx.mock(AgentRunningBuild.class);
  final BuildProgressLogger logger = new NullBuildProgressLogger();
  workingDir = createTempDir();

  mockeryCtx.checking(new Expectations() {{
    allowing(myContext).getWorkingDirectory();
    will(returnValue(workingDir));
    allowing(myContext).getBuild();
    will(returnValue(build));
    allowing(myContext).getRunnerParameters();
    will(returnValue(myRunnerParameters));
    allowing(build).getBuildLogger();
    will(returnValue(logger));
  }});

  myRunnerParameters.put(DeployerRunnerConstants.PARAM_CONTAINER_TYPE, "tomcat7x");
}
 
Example 20
Source File: KubeCloudInstanceImplTest.java    From teamcity-kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    super.setUp();
    m = new Mockery();
    myApi = m.mock(KubeApiConnector.class);
}