org.jmock.Expectations Java Examples

The following examples show how to use org.jmock.Expectations. 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: WicketUtilTest.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Test
public void testPageParametersAsMap() throws Exception {

    final CommandConfig commandConfig = context.mock(CommandConfig.class, "config");

    context.checking(new Expectations() {{
        allowing(commandConfig).isCommandKey("asd"); will(returnValue(false));
        allowing(commandConfig).isCommandKey("cmd1"); will(returnValue(true));
        allowing(commandConfig).isCommandKey("cmd2"); will(returnValue(true));

        allowing(commandConfig).isInternalCommandKey("asd"); will(returnValue(false));
        allowing(commandConfig).isInternalCommandKey("cmd1"); will(returnValue(true));
        allowing(commandConfig).isInternalCommandKey("cmd2"); will(returnValue(false));
    }});

    PageParameters parametersToFilter = new PageParameters()
        .add("cmd1", "val1")
        .add("asd", "dsa")
        .add("cmd2", "ppp");
    assertEquals(3, parametersToFilter.getNamedKeys().size());
    Map<String, String> filtered = new WicketUtil(commandConfig).pageParametersAsMap(parametersToFilter);
    assertNotNull(filtered);
    assertEquals(2, filtered.size());
    assertEquals("ppp", filtered.get("cmd2"));
    assertEquals("dsa", filtered.get("asd"));
}
 
Example #2
Source File: AbstractCommandsSupportJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void test008GetMemberWithMatchingMemberName() {
  final Cache mockCache = mockContext.mock(Cache.class, "Cache");

  final DistributedSystem mockDistributedSystem = mockContext.mock(DistributedSystem.class, "DistributedSystem");

  final DistributedMember mockMemberSelf = createMockMember("S", "Self");
  final DistributedMember mockMemberOne = createMockMember("1", "One");
  final DistributedMember mockMemberTwo = createMockMember("2", "Two");

  mockContext.checking(new Expectations() {{
    oneOf(mockCache).getMembers();
    will(returnValue(CollectionUtils.asSet(mockMemberOne, mockMemberTwo)));
    oneOf(mockCache).getDistributedSystem();
    will(returnValue(mockDistributedSystem));
    oneOf(mockDistributedSystem).getDistributedMember();
    will(returnValue(mockMemberSelf));
  }});

  final AbstractCommandsSupport commands = createAbstractCommandsSupport(mockCache);

  assertSame(mockMemberOne, commands.getMember(mockCache, "One"));
}
 
Example #3
Source File: EncodedSequentialLogTest.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
@Test
public void delegatesToItsNavigatorToReturnTheLastEntryInANonEmptyLog() throws Exception {
  final OLogEntry lastEntry = anOLogEntry();

  context.checking(new Expectations() {{
    oneOf(persistence).isEmpty();
    will(returnValue(false));

    oneOf(navigator).getStreamAtLastEntry();
    will(returnValue(aMockInputStream()));

    oneOf(codec).decode(with(any(InputStream.class)));
    will(returnValue(lastEntry));
  }});

  assertThat(log.getLastEntry(), equalTo(lastEntry));
}
 
Example #4
Source File: ThemeServiceImplTest.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCurrentThemeChainWhenShopUrlNullDefaultThemeCfgNull() throws Exception {

    final ShopService shopService = mockery.mock(ShopService.class, "shopService");

    final Shop shop = mockery.mock(Shop.class, "shop");

    mockery.checking(new Expectations() {{
        allowing(shopService).getById(1L);
        will(returnValue(shop));
        allowing(shop).getShopUrl();
        will(returnValue(null));
        allowing(shop).getFspointer();
        will(returnValue(null));
    }});

    final ThemeServiceImpl themeService = new ThemeServiceImpl(shopService);

    final List<String> chain0 = themeService.getThemeChainByShopId(1L, "www.default.com");
    assertNotNull(chain0);
    assertEquals(1, chain0.size());
    assertEquals("default", chain0.get(0));

    mockery.assertIsSatisfied();

}
 
Example #5
Source File: AbstractUiXmlLoaderTest.java    From mini2Dx with Apache License 2.0 6 votes vote down vote up
protected <T> T loadFileWithModel(String xml, T model) {
    final String realXml = "<?xml version=\"1.0\"?>\n" + xml;

    FileHandle fileHandle = mockery.mock(FileHandle.class);

    mockery.checking(new Expectations() {
        {
            oneOf(fileHandleResolver).resolve(filename);
            will(returnValue(fileHandle));
            try {
                oneOf(fileHandle).reader();
                will(returnValue(new StringReader(realXml)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    return loader.load(filename, model);
}
 
Example #6
Source File: CodaDocHead_validateBuyer_Test.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Test
public void when_buyer_does_have_ECP_role() throws Exception {

    // given
    assertThat(organisationWithRole.hasPartyRoleType(ecpRoleType)).isTrue();

    // expecting
    context.checking(new Expectations() {{
        allowing(mockPartyRepository).findPartyByReference("IT01");
        will(returnValue(organisationWithRole));
    }});

    // when
    codaDocHead.validateBuyer();

    // then
    assertThat(codaDocHead.getCmpCodeValidationStatus()).isEqualTo(ValidationStatus.VALID);
    assertThat(codaDocHead.getCmpCodeBuyer()).isEqualTo(organisationWithRole);
    assertThat(codaDocHead.getReasonInvalid()).isNull();
}
 
Example #7
Source File: ConnectionTest.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Test
public void testRollback() throws Exception {
	ShardConnection conn = new ShardConnection(filters);

	Map<String, Connection> actualConnections = new HashMap<String, Connection>();
	final Connection conn1 = context.mock(Connection.class, "conn1");
	final Connection conn2 = context.mock(Connection.class, "conn2");
	actualConnections.put("test-conn1", conn1);
	actualConnections.put("test-conn2", conn2);
	conn.setActualConnections(actualConnections);
	conn.setAutoCommit(false);

	context.checking(new Expectations() {
		{
			try {
				oneOf(conn1).rollback();
				oneOf(conn2).rollback();
			} catch (SQLException e) {
			}
		}
	});

	conn.rollback();
	context.assertIsSatisfied();

}
 
Example #8
Source File: PricingPolicyProviderCustomerAttributeImplTest.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeterminePricingPolicyCustomer() throws Exception {

    final CustomerService customerService = context.mock(CustomerService.class, "customerService");
    final ShopService shopService = context.mock(ShopService.class, "shopService");

    final Shop shop = context.mock(Shop.class, "shop");
    final Customer customer = context.mock(Customer.class, "customer");

    context.checking(new Expectations() {{
        allowing(shopService).getShopByCode("SHOP10"); will(returnValue(shop));
        allowing(customerService).getCustomerByEmail("[email protected]", shop); will(returnValue(customer));
        allowing(customer).getPricingPolicy(); will(returnValue("BOB"));
    }});

    final PricingPolicyProviderCustomerAttributeImpl provider = new PricingPolicyProviderCustomerAttributeImpl(customerService, shopService);

    PricingPolicyProvider.PricingPolicy policy;

    policy = provider.determinePricingPolicy("SHOP10", "EUR", "[email protected]", "GB", "GB-CAM");
    assertEquals(PricingPolicyProvider.PricingPolicy.Type.CUSTOMER, policy.getType());
    assertEquals("BOB", policy.getID());

    context.assertIsSatisfied();

}
 
Example #9
Source File: UnpagedListDisplayTagTest.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
public void testTitle() throws JspException {
    context().checking(new Expectations() { {
        atLeast(1).of(context).popBody();
        atLeast(1).of(context).pushBody();
        atLeast(1).of(request).getParameter(RequestContext.LIST_DISPLAY_EXPORT);
        will(returnValue(null));
        atLeast(1).of(request).getParameter(RequestContext.LIST_SORT);
        will(returnValue(null));
    } });

    writer.setExpectedData(EXPECTED_HTML_OUT_WITH_TITLE);

    ldt.setTitle("Inactive Systems");
    int tagval = ldt.doStartTag();
    assertEquals(Tag.EVAL_BODY_INCLUDE, tagval);
    tagval = ldt.doEndTag();
    ldt.release();
    assertEquals(Tag.EVAL_PAGE, tagval);
}
 
Example #10
Source File: ScapManagerTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
public void testXccdfEvalError() throws Exception {
    MinionServer minion = MinionServerFactoryTest.createTestMinionServer(user);
    SystemManager.giveCapability(minion.getId(), SystemManager.CAP_SCAP, 1L);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    ActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        allowing(taskomaticMock).scheduleActionExecution(with(any(Action.class)));
    } });

    ScapAction action = ActionManager.scheduleXccdfEval(user,
            minion, "/usr/share/openscap/scap-yast2sec-xccdf.xml", "--profile Default", new Date());

    File resumeXsl = new File(TestUtils.findTestData(
            "/com/redhat/rhn/manager/audit/test/openscap/minionsles12sp1.test.local/xccdf-resume.xslt.in").getPath());
    InputStream resultsIn = TestUtils.findTestData(
            "/com/redhat/rhn/manager/audit/test/openscap/minionsles12sp1.test.local/results_malformed.xml")
            .openStream();
    try {
        XccdfTestResult result = ScapManager.xccdfEval(minion, action, 2, "", resultsIn, resumeXsl);
        fail("Expected exception");
    } catch (Exception e) {
        assertTrue(e instanceof RuntimeException);
    }
}
 
Example #11
Source File: ReplicatorAppendEntriesTest.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
@Test
public void willLogANewQuorumConfigurationItReceivesAndUpdateItsCurrentConfiguration() throws Exception {
  final QuorumConfiguration configuration = aNewConfiguration();
  final List<LogEntry> receivedEntries = entries()
      .term(1)
      .configurationAndIndex(configuration, 1)
      .build();

  context.checking(new Expectations() {{
    oneOf(log).logEntries(receivedEntries);
  }});

  havingReceived(
      anAppendEntriesRequest()
          .withEntries(receivedEntries));

  assertThat(reply(), is(anAppendReply().withResult(true)));
  assertThat(replicatorInstance.getQuorumConfiguration().get(), is(equalTo(configuration)));
}
 
Example #12
Source File: WicketUtilTest.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFilteredRequestParameters() throws Exception {

    final CommandConfig commandConfig = context.mock(CommandConfig.class, "config");

    context.checking(new Expectations() {{
        allowing(commandConfig).isCommandKey("asd"); will(returnValue(false));
        allowing(commandConfig).isCommandKey("cmd1"); will(returnValue(true));
        allowing(commandConfig).isCommandKey("cmd2"); will(returnValue(true));
    }});

    assertNotNull(new WicketUtil(commandConfig).getFilteredRequestParameters(null));
    PageParameters parametersToFilter = new PageParameters()
        .add("cmd1", "val1")
        .add("asd", "dsa")
        .add("cmd2", "ppp");
    assertEquals(3, parametersToFilter.getNamedKeys().size());
    PageParameters filtered = new WicketUtil(commandConfig).getFilteredRequestParameters(parametersToFilter);
    assertNotNull(filtered);
    assertEquals(1, filtered.getNamedKeys().size());
    assertEquals("dsa", filtered.get("asd").toString());
}
 
Example #13
Source File: CodaDocHead_validateBuyer_Test.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Test
public void when_no_such_buyer() throws Exception {

    // expecting
    context.checking(new Expectations() {{
        allowing(mockPartyRepository).findPartyByReference("IT01");
        will(returnValue(null));
    }});

    // when
    codaDocHead.validateBuyer();

    // then
    assertThat(codaDocHead.getCmpCodeValidationStatus()).isEqualTo(ValidationStatus.INVALID);
    assertThat(codaDocHead.getCmpCodeBuyer()).isNull();
    assertThat(codaDocHead.getReasonInvalid()).isEqualTo("No buyer party found for cmpCode 'IT01'");
}
 
Example #14
Source File: QuorumDelegatingLogUnitTest.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
@Before
public void setUpMockedFactories() throws Exception {
  context.checking(new Expectations() {{
    allowing(navigatorFactory).create(with(any(BytePersistence.class)),
        with.<SequentialEntryCodec<?>>is(any(SequentialEntryCodec.class)),
        with(any(Long.class)));
    will(returnValue(persistenceNavigator));

    allowing(OLogEntryOracleFactory).create();
    will(returnValue(oLogEntryOracle));

    atMost(1).of(oLogEntryOracle).notifyLogging(with(any(OLogEntry.class)));

    allowing(oLogEntryOracle).getGreatestSeqNum();

    allowing(persistenceNavigator).getStreamAtFirstEntry();
    will(returnValue(aZeroLengthInputStream()));
  }});
}
 
Example #15
Source File: PxtSessionDelegateImplTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void setUp() throws Exception {
    super.setUp();

    mockRequest = mock(HttpServletRequest.class);
    mockResponse = mock(HttpServletResponse.class);
    mockPxtSession = mock(WebSession.class);
    mockHttpSession = mock(HttpSession.class);
    pxtSessionDelegate = new PxtSessionDelegateImplStub();
    pxtCookieManager = new PxtCookieManager();

    context().checking(new Expectations() { {
        allowing(mockRequest).getServerName();
        will(returnValue("somehost.redhat.com"));
        allowing(mockRequest).getHeader("User-Agent");
        will(returnValue(null));
    } });
}
 
Example #16
Source File: AbstractCommandsSupportJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void test013Register() {
  final Function mockFunction = mockContext.mock(Function.class, "Function");

  mockContext.checking(new Expectations() {{
    exactly(3).of(mockFunction).getId();
    will(returnValue("mockId"));
    oneOf(mockFunction).isHA();
    will(returnValue(true));
    oneOf(mockFunction).hasResult();
    will(returnValue(true));
  }});

  final AbstractCommandsSupport commands = createAbstractCommandsSupport(mockContext.mock(Cache.class));

  assertFalse(FunctionService.isRegistered("mockId"));
  assertSame(mockFunction, commands.register(mockFunction));
  assertTrue(FunctionService.isRegistered("mockId"));
}
 
Example #17
Source File: PxtSessionDelegateImplTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
public final void testLoadPxtSessionWhenPxtSessionIdIsNotNull() {
    setUpLoadPxtSession();

    context().checking(new Expectations() { {
        allowing(mockRequest).getCookies();
        will(returnValue(new Cookie[] {getPxtCookie()}));
    } });

    pxtSessionDelegate.setFindPxtSessionByIdCallback(new Transformer() {
        public Object transform(Object arg) {
            if (PXT_SESSION_ID.equals(arg)) {
                return getPxtSession();
            }
            return null;
        }
    });

    pxtSessionDelegate.loadPxtSession(getRequest());
}
 
Example #18
Source File: ArtifactPathHelperTest.java    From teamcity-symbol-server with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "testPaths")
public void testPathTransformation(String prefix, String fileName, String expectedPath) {
  Mockery m = new Mockery();
  ExtensionHolder extensionHolder = m.mock(ExtensionHolder.class);
  BuildProgressLogger logger = m.mock(BuildProgressLogger.class);
  InternalPropertiesHolder propertiesHolder = m.mock(InternalPropertiesHolder.class);
  ArtifactPathHelper helper = new ArtifactPathHelper(extensionHolder);
  ZipPreprocessor zipPreprocessor = new ZipPreprocessor(logger, new File("."), propertiesHolder);

  m.checking(new Expectations(){{
    allowing(extensionHolder).getExtensions(with(ArchivePreprocessor.class));
    will(returnValue(Collections.singletonList(zipPreprocessor)));
  }});

  Assert.assertEquals(helper.concatenateArtifactPath(prefix, fileName), expectedPath);
}
 
Example #19
Source File: SimpleRequestServiceTest.java    From Spring with Apache License 2.0 6 votes vote down vote up
@Test
public void findByIdPositive() {
    final Request req = new Request();
    req.setId(REQUEST_ID);
    req.setStartAt(DateTime.parse("2016-09-06").toDate());
    req.setEndAt(DateTime.parse("2016-09-18").toDate());
    req.setRequestStatus(RequestStatus.NEW);

    mockery.checking(new Expectations() {{
        allowing(requestMockRepo).findById(REQUEST_ID);
        will(returnValue(req));
    }});

    final Request result = simpleRequestService.findById(REQUEST_ID);
    mockery.assertIsSatisfied();
    assertNotNull(result);
    assertEquals(req.getId(), result.getId());
}
 
Example #20
Source File: DocumentServiceRestApi_uploadGeneric_Test.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Test
public void when_using_unsupported_doc_type_data() throws Exception {

    // given
    final Blob blob = new Blob("Foo", MimeTypeData.APPLICATION_PDF.asStr(), new byte[20]);

    // expect
    context.checking(new Expectations() {{
        oneOf(mockDocumentTypeRepository).findByReference("INCOMING_ORDER");
    }});
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("DocumentType INCOMING_ORDER is not supported");

    // when
    service.uploadGeneric(blob, "INCOMING_ORDER", "/ITA");

}
 
Example #21
Source File: ServerLauncherJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsDefaultServerEnabled() {
  final Cache mockCache = mockContext.mock(Cache.class, "Cache");

  mockContext.checking(new Expectations() {{
    oneOf(mockCache).getCacheServers();
    will(returnValue(Collections.emptyList()));
  }});

  ServerLauncher serverLauncher = new Builder().setMemberName("serverOne").build();

  assertNotNull(serverLauncher);
  assertEquals("serverOne", serverLauncher.getMemberName());
  assertFalse(serverLauncher.isDisableDefaultServer());
  assertTrue(serverLauncher.isDefaultServerEnabled(mockCache));
}
 
Example #22
Source File: ShipTypeAndSizeAnalysisTest.java    From AisAbnormal with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void abnormalWhereNoShipCountStatistics() {
    // Assert that pre-conditions are as expected
    assertNull(statistics1.getValue((short) 1, (short) 1, "shipCount"));

    // Setup expectations
    final ArgumentCaptor<Analysis> analysisCaptor = ArgumentCaptor.forClass(Analysis.class);
    context.checking(new Expectations() {{
        oneOf(behaviourManager).registerSubscriber(with(any(ShipTypeAndSizeAnalysis.class)));
        oneOf(trackingService).registerSubscriber(with(analysisCaptor.getMatcher()));
        oneOf(statisticsRepository).getStatisticData("ShipTypeAndSizeStatistic", testCellId); will(returnValue(statistics1));
        ignoring(statisticsService).incAnalysisStatistics(with(ShipTypeAndSizeAnalysis.class.getSimpleName()), with(any(String.class)));
    }});

    // Create object under test
    final ShipTypeAndSizeAnalysis analysis = new ShipTypeAndSizeAnalysis(configuration, statisticsService, statisticsRepository, trackingService, eventRepository, behaviourManager);
    analysis.start();

    // Perform test
    boolean isAbnormalEvent = analysis.isAbnormalCellForShipTypeAndSize(testCellId, (short) 1, (short) 1);

    // Assert results
    context.assertIsSatisfied();
    assertEquals(analysis, analysisCaptor.getCapturedObject());
    assertTrue(isAbnormalEvent);
}
 
Example #23
Source File: FopThemeResourceResolverTest.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetResourceFromContent() throws Exception {

    context.checking(new Expectations() {{
        allowing(shop).getShopId(); will(returnValue(123L));
        allowing(shop).getCode(); will(returnValue("SHOP10"));
        oneOf(contentService).getContentBody("SHOP10_report_fop-config.xml", "en"); will(returnValue("xml contents"));
    }});

    final FopThemeResourceResolver resolver =
            new FopThemeResourceResolver(shop, lang, themeService, contentService, servletContext, systemService, imageService);

    assertNotNull(resolver.getResource(new URI("fop-config.xml")));

    context.assertIsSatisfied();

}
 
Example #24
Source File: UnpagedListDisplayTagTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
public void setUp() throws Exception {
    super.setUp();
    setImposteriser(ClassImposteriser.INSTANCE);
    RhnBaseTestCase.disableLocalizationServiceLogging();

    request = mock(HttpServletRequest.class);
    response = mock(HttpServletResponse.class);
    context = mock(PageContext.class);
    writer = new RhnMockJspWriter();

    ldt = new UnpagedListDisplayTag();
    lt = new ListTag();
    ldt.setPageContext(context);
    ldt.setParent(lt);

    lt.setPageList(new DataResult(CSVWriterTest.getTestListOfMaps()));

    context().checking(new Expectations() { {
        atLeast(1).of(context).getOut();
        will(returnValue(writer));
        atLeast(1).of(context).getRequest();
        will(returnValue(request));
        atLeast(1).of(context).setAttribute("current", null);
    } });
}
 
Example #25
Source File: SuddenSpeedChangeAnalysisTest.java    From AisAbnormal with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void noEventIsRaisedWhenTrackHasBeenStale() {
    // Perform test - none of the required data are there
    context.checking(new Expectations() {{
        never(eventRepository).save(with(any(Event.class)));
    }});
    analysis.start();

    int deltaSecs = 7;

    PositionChangedEvent event = new PositionChangedEvent(track, null);
    track.update(track.getTimeOfLastPositionReport() + (deltaSecs + 0) * 1000, Position.create(56, 12), 45.0f, 12.2f, 45.0f);
    analysis.onSpeedOverGroundUpdated(event);

    track.update(track.getTimeOfLastPositionReport() + (deltaSecs + 1) * 1000, Position.create(56, 12), 45.0f, 0.1f, 45.0f);
    analysis.onSpeedOverGroundUpdated(event);
    TrackStaleEvent staleEvent = new TrackStaleEvent(track);
    analysis.onTrackStale(staleEvent);

    track.update(track.getTimeOfLastPositionReport() + (deltaSecs + 24*60*60) * 1000, Position.create(56, 12), 45.0f, 0.1f, 45.0f);
    analysis.onSpeedOverGroundUpdated(event);

    context.assertIsSatisfied();
}
 
Example #26
Source File: IncomingInvoiceMenu_Test.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Test
public void filterOrFindBySeller_find_works() {

    IncomingInvoiceMenu.IncomingInvoiceFinder builder;

    // given
    builder = new IncomingInvoiceMenu.IncomingInvoiceFinder(mockInvoiceRepository, mockIncomingInvoiceRepository, mockPartyRepository);
    Organisation seller = new Organisation();

    // expect
    context.checking(new Expectations(){{
        oneOf(mockPartyRepository).findParties("*abc*");
        will(returnValue(Arrays.asList(seller)));
        oneOf(mockInvoiceRepository).findBySeller(seller);
    }});

    // when
    builder.filterOrFindBySeller("abc");

}
 
Example #27
Source File: EncodingSpecificDatatypeCoderTest.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void decodeString_delegatesToEncoding() throws Exception {
    final byte[] inputValue = { 1, 2, 3, 4};
    final String resultValue = "result value";

    context.checking(new Expectations() {{
        oneOf(encoding).decodeFromCharset(inputValue); will(returnValue(resultValue));
    }});

    String result = coder.decodeString(inputValue);

    assertEquals(resultValue, result);
}
 
Example #28
Source File: TestGeneratedKeysQuery.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test generated keys for the case of passing a normal INSERT and indexed columns, in order of ordinal position.
 * <p>
 * <ul>
 * <li>generatesKeys() returns {@code true}</li>
 * <li>getQueryString() returns query RETURNING clause with columns specified unquoted</li>
 * </ul>
 * </p>
 */
@Test
public void testGeneratedKeys_columnIndexes_dialect1() throws SQLException {
    initDefaultGeneratedKeysSupport(3, 0);
    expectConnectionDialectCheck(1);
    context.checking(new Expectations() {{
        // Metadata for table in query will be retrieved
        oneOf(dbMetadata).getColumns(null, null, "GENERATED\\_KEYS\\_TBL", null);
        will(returnValue(columnRs));
        // We want to return three columns, so for next() three return true, fourth returns false
        exactly(4).of(columnRs).next();
        will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(true),
                returnValue(false)));
        // NOTE: Implementation detail that this calls getString for column 4 (COLUMN_NAME) twice
        exactly(2).of(columnRs).getString(4);
        will(onConsecutiveCalls(returnValue("ID"), returnValue("NAME")));
        // NOTE: Implementation detail that this calls getInt for column 17 (ORDINAL_POSITION)
        exactly(3).of(columnRs).getInt(17);
        will(onConsecutiveCalls(returnValue(1), returnValue(2), returnValue(3)));
        oneOf(columnRs).close();
    }});

    // NOTE Implementation detail
    final String expectedSuffix = "\nRETURNING ID,NAME";

    GeneratedKeysSupport.Query query = generatedKeysSupport
            .buildQuery(TEST_INSERT_QUERY, new int[] { 1, 2 });

    assertTrue("Query with columnIndexes should generate keys", query.generatesKeys());
    assertThat("Query has RETURNING clauses added", query.getQueryString(), allOf(
            not(equalTo(TEST_INSERT_QUERY)),
            startsWith(TEST_INSERT_QUERY),
            endsWith(expectedSuffix)));
}
 
Example #29
Source File: NumeratorForOutgoingInvoicesRepository_Test.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Test
public void createCollectionNumberNumerator() {
    context.checking(new Expectations() {
        {
            oneOf(mockNumeratorRepository).create(
                    NumeratorForOutgoingInvoicesRepository.COLLECTION_NUMBER, null, null, null, format, lastIncrement, globalApplicationTenancy);
        }
    });
    numeratorForOutgoingInvoicesRepository.createCollectionNumberNumerator(format, lastIncrement);
}
 
Example #30
Source File: LeaseItem_Test.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Test
public void testChoices() throws Exception {

    // given
    leaseItem = new LeaseItem();
    leaseItem.setLease(lease);
    leaseItem.leaseItemSourceRepository = mockLeaseItemSourceRepository;

    LeaseItemSource leaseItemSource = new LeaseItemSource();
    leaseItemSource.setItem(leaseItem);
    leaseItemSource.setSourceItem(itemLinked);

    context.checking(new Expectations() {
        {
            allowing(mockLeaseItemSourceRepository).findByItem(leaseItem);
            will(returnValue(Arrays.asList(leaseItemSource)));
        }
    });

    // when
    List<LeaseItem> choices = leaseItem.choices0NewSourceItem(leaseItem);

    // then
    assertThat(leaseItem.getLease().getItems()).hasSize(3);
    assertThat(choices).hasSize(1);
    assertThat(choices.get(0)).isEqualTo(itemNotLinked);

}