method2testcases
stringlengths
118
6.63k
### Question: FsMountPoint implements Serializable, Comparable<FsMountPoint> { public static FsMountPoint create(URI uri) { return create(uri, NULL); } @ConstructorProperties("uri") FsMountPoint(URI uri); FsMountPoint(URI uri, FsUriModifier modifier); FsMountPoint(final FsScheme scheme, final FsNodePath path); static FsMountPoint create(URI uri); static FsMountPoint create(URI uri, FsUriModifier modifier); static FsMountPoint create(FsScheme scheme, FsNodePath path); URI getUri(); URI toHierarchicalUri(); FsScheme getScheme(); @Nullable FsNodePath getPath(); @Nullable FsMountPoint getParent(); FsNodePath resolve(FsNodeName name); @Override int compareTo(FsMountPoint that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); static final String SEPARATOR; }### Answer: @Test @SuppressWarnings("ResultOfObjectAllocationIgnored") public void testConstructorWithInvalidUri() throws URISyntaxException { try { FsMountPoint.create((URI) null); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((URI) null); fail(); } catch (NullPointerException expected) { } try { FsMountPoint.create((URI) null, NULL); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((URI) null, NULL); fail(); } catch (NullPointerException expected) { } try { FsMountPoint.create((URI) null, CANONICALIZE); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((URI) null, CANONICALIZE); fail(); } catch (NullPointerException expected) { } try { FsMountPoint.create((FsScheme) null, null); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((FsScheme) null, null); fail(); } catch (NullPointerException expected) { } for (final String param : new String[] { "foo:/?queryDefined", "foo:bar:baz:/!/!/", "foo", "foo/bar", "foo/bar/", "/foo", "/foo/bar", "/foo/bar/", " "/../foo", "foo:/bar#baz", "foo:/bar/#baz", "foo:/bar", "foo:/bar?baz", "foo:/bar "foo:/bar/.", "foo:/bar/./", "foo:/bar/..", "foo:/bar/../", "foo:bar!/", "foo:bar:baz!/", "foo:bar:/baz! "foo:bar:/baz!/.", "foo:bar:/baz!/./", "foo:bar:/baz!/..", "foo:bar:/baz!/../", "foo:bar:/baz!/bang", "foo:bar:/baz!/#bang", "foo:bar:/baz/!/", "foo:bar:baz:/bang!/!/", }) { final URI uri = URI.create(param); try { FsMountPoint.create(uri); fail(param); } catch (IllegalArgumentException expected) { } try { new FsMountPoint(uri); fail(param); } catch (URISyntaxException expected) { } } for (final String[] params : new String[][] { { "foo", "bar:baz:/bang!/" }, { "foo", "bar:/baz/" }, }) { final FsScheme scheme = FsScheme.create(params[0]); final FsNodePath path = FsNodePath.create(URI.create(params[1])); try { new FsMountPoint(scheme, path); fail(params[0] + ":" + params[1] + "!/"); } catch (URISyntaxException expected) { } } }
### Question: FsMountPoint implements Serializable, Comparable<FsMountPoint> { public FsNodePath resolve(FsNodeName name) { return new FsNodePath(this, name); } @ConstructorProperties("uri") FsMountPoint(URI uri); FsMountPoint(URI uri, FsUriModifier modifier); FsMountPoint(final FsScheme scheme, final FsNodePath path); static FsMountPoint create(URI uri); static FsMountPoint create(URI uri, FsUriModifier modifier); static FsMountPoint create(FsScheme scheme, FsNodePath path); URI getUri(); URI toHierarchicalUri(); FsScheme getScheme(); @Nullable FsNodePath getPath(); @Nullable FsMountPoint getParent(); FsNodePath resolve(FsNodeName name); @Override int compareTo(FsMountPoint that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); static final String SEPARATOR; }### Answer: @Test public void testResolve() { for (final String[] params : new String[][] { { "foo:bar:/baz?plonk!/", "", "baz", "foo:bar:/baz?plonk!/" }, { "foo:bar:/bäz?bööm!/", "bäng?plönk", "bäz/bäng?plönk", "foo:bar:/bäz?bööm!/bäng?plönk" }, { "foo:bar:/baz!/", "bang?boom", "baz/bang?boom", "foo:bar:/baz!/bang?boom" }, { "foo:bar:/baz!/", "bang", "baz/bang", "foo:bar:/baz!/bang" }, { "foo:bar:/baz!/", "", "baz", "foo:bar:/baz!/" }, { "foo:bar:/baz?plonk!/", "bang?boom", "baz/bang?boom", "foo:bar:/baz?plonk!/bang?boom" }, { "foo:bar:/baz?plonk!/", "bang", "baz/bang", "foo:bar:/baz?plonk!/bang" }, { "foo:/bar/", "baz?bang", null, "foo:/bar/baz?bang" }, { "foo:/bar/", "baz", null, "foo:/bar/baz" }, { "foo:/bar/", "", null, "foo:/bar/" }, { "foo:/bar/", "baz", null, "foo:/bar/baz" }, }) { final FsMountPoint mountPoint = FsMountPoint.create(URI.create(params[0])); final FsNodeName entryName = FsNodeName.create(URI.create(params[1])); final FsNodeName parentEntryName = null == params[2] ? null : FsNodeName.create(URI.create(params[2])); final FsNodePath path = FsNodePath.create(URI.create(params[3])); if (null != parentEntryName) assertThat(mountPoint.getPath().resolve(entryName).getNodeName(), equalTo(parentEntryName)); assertThat(mountPoint.resolve(entryName), equalTo(path)); assertThat(mountPoint.resolve(entryName).getUri().isAbsolute(), is(true)); } }
### Question: User implements Serializable { public User(final String login, final String password) { this.login = login; this.password = password; } User(final String login, final String password); final void setLocale(final String locale); final Date getLastUpdate(); final void setLastUpdate(final Date lastUpdate); final void setDatePattern(final String datePattern); final String getLanguage(); final String getCountry(); final JsonObject getJSONObject(); }### Answer: @Test public void testUser() { String login = "carl"; String password = "mypassword"; String email = "[email protected]"; User user = User.builder().login(login).password(password).email(email).build(); assertEquals(login, user.getLogin()); assertEquals(email, user.getEmail()); }
### Question: Portfolio { public final Optional<Account> getAccount(final String name) { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> account.getName().equals(name)).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetAccountByName() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getAccount(FIDELITY); assertTrue(actual.isPresent()); } @Test public void testGetAccountById() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getAccount(2); assertTrue(actual.isPresent()); } @Test public void testGetAccountByIdEmpty() { Optional<Account> actual = portfolio.getAccount(2); assertFalse(actual.isPresent()); }
### Question: Portfolio { public final Optional<Account> getFirstAccount() { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> !account.getDel()).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetFirstAccount() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getFirstAccount(); assertTrue(actual.isPresent()); }
### Question: Portfolio { protected Map<String, List<Equity>> getSectorByCompanies() { final Map<String, List<Equity>> map = new TreeMap<>(); List<Equity> companies; for (final Equity equity : getEquities()) { if (equity.getCompany().getFund()) { companies = map.getOrDefault(Constants.FUND, new ArrayList<>()); companies.add(equity); map.putIfAbsent(Constants.FUND, companies); } else { final String sector = equity.getCurrentSector(); if (StringUtils.isEmpty(sector)) { companies = map.getOrDefault(Constants.UNKNOWN, new ArrayList<>()); companies.add(equity); map.putIfAbsent(Constants.UNKNOWN, companies); } else { companies = map.getOrDefault(sector, new ArrayList<>()); companies.add(equity); map.putIfAbsent(sector, companies); } } } return map; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetSectorByCompanies() { portfolio.setEquities(createEquities()); Map<String, List<Equity>> actual = portfolio.getSectorByCompanies(); assertNotNull(actual); assertThat(actual.size(), is(3)); assertTrue(actual.containsKey(FUND)); assertTrue(actual.containsKey(UNKNOWN)); assertTrue(actual.containsKey(HIGH_TECH)); }
### Question: Portfolio { public final String getHTMLSectorByCompanies() { final Map<String, List<Equity>> map = getSectorByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetHTMLSectorByCompanies() { portfolio.setEquities(createEquities()); String actual = portfolio.getHTMLSectorByCompanies(); verifyHTML(actual); }
### Question: Portfolio { protected Map<String, List<Equity>> getGapByCompanies() { final Map<String, List<Equity>> map = new TreeMap<>(); List<Equity> companies; for (final Equity equity : getEquities()) { if (equity.getMarketCapitalizationType().getValue() == null || equity.getCompany().getFund()) { equity.setMarketCapitalizationType(MarketCapitalization.UNKNOWN); } companies = map.getOrDefault(equity.getMarketCapitalizationType().getValue(), new ArrayList<>()); companies.add(equity); map.put(equity.getMarketCapitalizationType().getValue(), companies); } return map; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetGapByCompanies() { portfolio.setEquities(createEquities()); Map<String, List<Equity>> actual = portfolio.getGapByCompanies(); assertNotNull(actual); assertThat(actual.size(), is(3)); assertTrue(actual.containsKey(LARGE_CAP.getValue())); assertTrue(actual.containsKey(MEGA_CAP.getValue())); assertTrue(actual.containsKey(UNKNOWN)); }
### Question: Portfolio { public final String getHTMLCapByCompanies() { final Map<String, List<Equity>> map = getGapByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetHTMLCapByCompanies() { portfolio.setEquities(createEquities()); String actual = portfolio.getHTMLCapByCompanies(); verifyHTML(actual); }
### Question: Portfolio { public final Double getTotalValue() { return totalValue + getLiquidity(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetTotalValue() { Double actual = portfolio.getTotalValue(); assertEquals(0d, actual, 0.1); } @Test public void testGetTotalValueWithLiquidity() { portfolio.setLiquidity(1000d); Double actual = portfolio.getTotalValue(); assertEquals(1000d, actual, 0.1); }
### Question: Portfolio { public final void compute() { Double totalUnitCostPrice = 0d; Double totalAverageQuotePrice = 0d; Double totalOriginalValue = 0d; totalVariation = 0d; double totalValueStart = 0; totalGainToday = 0d; Date lastUpdate = null; if (equities != null) { for (final Equity equity : equities) { totalQuantity += equity.getQuantity(); totalUnitCostPrice += equity.getUnitCostPrice(); totalAverageQuotePrice += equity.getCompany().getQuote() * equity.getParity(); totalValue += equity.getValue(); totalOriginalValue += equity.getQuantity() * equity.getUnitCostPrice() * equity.getCurrentParity(); yieldYear += equity.getYieldYear(); totalGain += equity.getPlusMinusUnitCostPriceValue(); if (equity.getCompany().getRealTime()) { if (lastUpdate == null) { lastUpdate = equity.getCompany().getLastUpdate(); } else { if (equity.getCompany().getLastUpdate() != null && lastUpdate.after(equity.getCompany().getLastUpdate())) { lastUpdate = equity.getCompany().getLastUpdate(); } } } if (equity.getCompany().getChange() != null) { double valueStart = equity.getValue() / (equity.getCompany().getChange() / PERCENT + 1); totalValueStart += valueStart; totalGainToday += valueStart * equity.getCompany().getChange() / PERCENT; } } totalVariation = totalValueStart == 0 ? totalValueStart : ((totalValueStart + totalGainToday) / totalValueStart - 1) * PERCENT; averageUnitCostPrice = totalUnitCostPrice / equities.size(); averageQuotePrice = totalAverageQuotePrice / equities.size(); totalPlusMinusValue = ((totalValue - totalOriginalValue) / totalOriginalValue) * PERCENT; yieldYearPerc = yieldYear / getTotalValue() * PERCENT; setLastCompanyUpdate(lastUpdate); } } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testCompute() { portfolio.setEquities(createEquities()); portfolio.compute(); assertEquals(66d, portfolio.getTotalQuantity(), 0.1); assertEquals(30500d, portfolio.getTotalValue(), 0.1); assertEquals(0d, portfolio.getYieldYear(), 0.1); assertEquals(12700d, portfolio.getTotalGain(), 0.1); assertNotNull(portfolio.getLastCompanyUpdate()); }
### Question: Portfolio { protected final Map<String, Double> getChartSectorData() { if (chartSectorData == null) { final Map<String, Double> data = new HashMap<>(); for (final Equity equity : getEquities()) { if (equity.getCompany().getFund()) { addEquityValueToMap(data, Constants.FUND, equity); } else { final String sector = equity.getCurrentSector(); if (StringUtils.isEmpty(sector)) { addEquityValueToMap(data, Constants.UNKNOWN, equity); } else { addEquityValueToMap(data, sector, equity); } } } chartSectorData = new TreeMap<>(); chartSectorData.putAll(data); } return chartSectorData; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetChartSectorData() { portfolio.setEquities(createEquities()); Map<String, Double> actual = portfolio.getChartSectorData(); assertNotNull(actual); assertEquals(25500d, actual.get(FUND), 0.1); assertEquals(4000d, actual.get(HIGH_TECH), 0.1); assertEquals(1000d, actual.get(UNKNOWN), 0.1); }
### Question: Portfolio { protected final Map<Date, Double> getChartShareValueData() { Map<Date, Double> data = new HashMap<>(); List<ShareValue> shareValuess = getShareValues(); int max = shareValuess.size(); double base = shareValuess.get(max - 1).getShareValue(); for (int i = max - 1; i != -1; i--) { ShareValue temp = shareValuess.get(i); Double value = temp.getShareValue() * PERCENT / base; data.put(temp.getDate(), value); } chartShareValueData = new TreeMap<>(); chartShareValueData.putAll(data); return chartShareValueData; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetChartShareValueData() { portfolio.setShareValues(createShareValues()); Map<Date, Double> actual = portfolio.getChartShareValueData(); assertNotNull(actual); assertThat(actual.size(), is(2)); Iterator<Date> iterator = actual.keySet().iterator(); assertEquals(100d, actual.get(iterator.next()), 0.1); assertEquals(50d, actual.get(iterator.next()), 0.1); }
### Question: Portfolio { protected final Map<String, Double> getChartCapData() { if (chartCapData == null) { Map<String, Double> data = new HashMap<>(); for (Equity equity : getEquities()) { if (!equity.getCompany().getFund()) { MarketCapitalization marketCap = equity.getMarketCapitalizationType(); if (marketCap == null) { addEquityValueToMap(data, Constants.UNKNOWN, equity); } else { addEquityValueToMap(data, marketCap.getValue(), equity); } } else { addEquityValueToMap(data, Constants.UNKNOWN, equity); } } chartCapData = new TreeMap<>(); chartCapData.putAll(data); } return chartCapData; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetChartCapData() { portfolio.setEquities(createEquities()); Map<String, Double> actual = portfolio.getChartCapData(); assertNotNull(actual); assertEquals(1000d, actual.get(MEGA_CAP.getValue()), 0.1); assertEquals(4000d, actual.get(LARGE_CAP.getValue()), 0.1); assertEquals(25500d, actual.get(UNKNOWN), 0.1); }
### Question: Portfolio { public final List<String> getCompaniesYahooIdRealTime() { return getEquities().stream() .filter(equity -> equity.getCompany().getRealTime()) .map(equity -> equity.getCompany().getYahooId()) .collect(Collectors.toList()); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetCompaniesYahooIdRealTime() { portfolio.setEquities(createEquities()); List<String> actual = portfolio.getCompaniesYahooIdRealTime(); assertNotNull(actual); assertThat(actual, containsInAnyOrder(GOOGLE, APPLE)); }
### Question: Portfolio { public final void addIndexes(final List<Index> indexes) { if (indexes.size() > 0) { String index = indexes.get(0).getYahooId(); this.indexes.put(index, indexes); } } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testAddIndexes() { final List<Index> indexes = new ArrayList<>(); final Index index = Index.builder().yahooId(CAC40).build(); indexes.add(index); portfolio.addIndexes(indexes); final Map<String, List<Index>> actual = portfolio.getIndexes(); assertNotNull(actual); assertThat(actual.size(), is(1)); assertNotNull(actual.get(CAC40)); }
### Question: Portfolio { public final String getPortfolioReview() { final StringBuilder sb = new StringBuilder(); sb.append("<table class=\"shareValueTableDetails\">"); for (final Equity equity : getEquities()) { sb.append("<tr><td width=200px><b>") .append(equity.getCurrentName()) .append("</b></td><td width=180px>") .append(equity.getQuantity()) .append(" * ") .append(equity.getCompany().getQuote()); if (equity.getCompany().getCurrency() != getCurrency()) { sb.append(" * ").append(getCurrency().getParity(equity.getCompany().getCurrency())); } sb.append("</td><td>").append(equity.getValue()).append(" (").append(getCurrency().getCode()).append(")</td></tr>"); } sb.append("<tr><td colspan=3><b>Liquidity:</b> ").append(getLiquidity()).append(" (").append(getCurrency().getCode()).append(")</td></tr>"); sb.append("<tr><td colspan=3><b>Total:</b> ").append(new BigDecimal(getTotalValue(), mathContext).doubleValue()).append(" (").append(getCurrency().getCode()).append(")</td></tr>"); sb.append("</table>"); return sb.toString(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer: @Test public void testGetPortfolioReview() { portfolio.setEquities(createEquities()); final String actual = portfolio.getPortfolioReview(); assertNotNull(actual); }
### Question: TokenUtils { public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.genKeyPair(); return keyPair; } private TokenUtils(); static String generateTokenString(String jsonResName); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims); static PrivateKey readPrivateKey(String pemResName); static PublicKey readPublicKey(String pemResName); static KeyPair generateKeyPair(int keySize); static PrivateKey decodePrivateKey(String pemEncoded); static PublicKey decodePublicKey(String pemEncoded); }### Answer: @Test public void testKeyPairGeneration() throws Exception { KeyPair keyPair = TokenUtils.generateKeyPair(2048); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); byte[] privateKeyEnc = privateKey.getEncoded(); byte[] privateKeyPem = Base64.getEncoder().encode(privateKeyEnc); String privateKeyPemStr = new String(privateKeyPem); System.out.println("-----BEGIN RSA PRIVATE KEY-----"); int column = 0; for (int n = 0; n < privateKeyPemStr.length(); n++) { System.out.print(privateKeyPemStr.charAt(n)); column++; if (column == 64) { System.out.println(); column = 0; } } System.out.println("\n-----END RSA PRIVATE KEY-----"); byte[] publicKeyEnc = publicKey.getEncoded(); byte[] publicKeyPem = Base64.getEncoder().encode(publicKeyEnc); String publicKeyPemStr = new String(publicKeyPem); System.out.println("-----BEGIN RSA PUBLIC KEY-----"); column = 0; for (int n = 0; n < publicKeyPemStr.length(); n++) { System.out.print(publicKeyPemStr.charAt(n)); column++; if (column == 64) { System.out.println(); column = 0; } } System.out.println("\n-----END RSA PUBLIC KEY-----"); }
### Question: TokenUtils { public static PrivateKey readPrivateKey(String pemResName) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName); byte[] tmp = new byte[4096]; int length = contentIS.read(tmp); PrivateKey privateKey = decodePrivateKey(new String(tmp, 0, length)); return privateKey; } private TokenUtils(); static String generateTokenString(String jsonResName); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims); static PrivateKey readPrivateKey(String pemResName); static PublicKey readPublicKey(String pemResName); static KeyPair generateKeyPair(int keySize); static PrivateKey decodePrivateKey(String pemEncoded); static PublicKey decodePublicKey(String pemEncoded); }### Answer: @Test public void testReadPrivateKey() throws Exception { PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey.pem"); System.out.println(privateKey); }
### Question: TokenUtils { public static PublicKey readPublicKey(String pemResName) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName); byte[] tmp = new byte[4096]; int length = contentIS.read(tmp); PublicKey publicKey = decodePublicKey(new String(tmp, 0, length)); return publicKey; } private TokenUtils(); static String generateTokenString(String jsonResName); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims); static PrivateKey readPrivateKey(String pemResName); static PublicKey readPublicKey(String pemResName); static KeyPair generateKeyPair(int keySize); static PrivateKey decodePrivateKey(String pemEncoded); static PublicKey decodePublicKey(String pemEncoded); }### Answer: @Test public void testReadPublicKey() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem"); System.out.println(publicKey); System.out.printf("RSAPublicKey.bitLength: %s\n", publicKey.getModulus().bitLength()); }
### Question: MicrometerMetricsRegistry implements MetricsRegistry { @Override public <T> Gauge gauge(String name, Collection<Tag> tags, T obj, ToDoubleFunction<T> f) { return new MicrometerGauge<T>(io.micrometer.core.instrument.Gauge.builder(name, obj, f).tags(toTags(tags)).register(registry)); } MicrometerMetricsRegistry(MeterRegistry registry); @Override Gauge gauge(String name, Collection<Tag> tags, T obj, ToDoubleFunction<T> f); @Override Counter counter(String name, Collection<Tag> tags); @Override Timer timer(String name, Collection<Tag> tags); }### Answer: @Test public void gaugeOnNullValue() { Gauge gauge = registry.gauge("gauge", emptyList(), null, obj -> 1.0); assertEquals(gauge.value(), Double.NaN, 0); }
### Question: Span implements io.opentracing.Span { @Override public void finish() { finishTrace(clock.microTime()); } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString(); @Override void finish(); @Override void finish(long finishMicros); Long getDuration(); Long getStartTime(); Tracer getTracer(); @Override SpanContext context(); String getServiceName(); String getOperationName(); @Override Span setOperationName(String operationName); @Override Span setBaggageItem(String key, String value); @Override String getBaggageItem(String key); Map<String, String> getBaggageItems(); @Override Span setTag(String key, Number value); @Override io.opentracing.Span setTag(Tag<T> tag, T value); @Override Span setTag(String key, boolean value); @Override Span setTag(String key, String value); Map<String, Object> getTags(); @Override Span log(long timestampMicroseconds, Map<String, ?> fields); @Override Span log(long timestampMicroseconds, String event); @Override Span log(Map<String, ?> fields); @Override Span log(String event); List<LogData> getLogs(); }### Answer: @Test public void testFinishAfterFinish() { InMemoryDispatcher dispatcher = new InMemoryDispatcher.Builder(metrics).build(); tracer = new Tracer.Builder(metrics, "remote-dispatcher", dispatcher).build(); Span span = tracer.buildSpan("operation").start(); span.finish(); try { span.finish(); Assert.fail(); } catch (IllegalStateException ex) { } try { dispatcher.flush(); } catch (IOException ex) { Assert.fail(); } Assert.assertEquals(0, dispatcher.getReportedSpans().size()); Assert.assertEquals(1, dispatcher.getFlushedSpans().size()); Assert.assertEquals(1, dispatcher.getReceivedSpans().size()); }
### Question: GRPCAgentClient extends BaseGrpcClient<Span> { @Override public boolean send(Span span) throws ClientException { try (Sample timer = sendTimer.start()) { stub.dispatch(format.format(span), observer); } catch (Exception e) { sendExceptionCounter.increment(); throw new ClientException(e.getMessage(), e); } return true; } GRPCAgentClient(Metrics metrics, Format<com.expedia.open.tracing.Span> format, ManagedChannel channel, SpanAgentStub stub, StreamObserver<DispatchResult> observer, long shutdownTimeoutMS); @Override boolean send(Span span); }### Answer: @Test public void testDispatch() throws Exception { final Span span = tracer.buildSpan("happy-path").start(); span.finish(); final ArgumentCaptor<com.expedia.open.tracing.Span> spanCapture = ArgumentCaptor.forClass(com.expedia.open.tracing.Span.class); client.send(span); verify(serviceImpl, times(1)).dispatch(spanCapture.capture(), Matchers.<StreamObserver<DispatchResult>>any()); }
### Question: HttpCollectorClient extends BaseHttpClient implements Client<Span> { @Override public boolean send(Span span) throws ClientException { final byte[] spanBytes = format.format(span).toByteArray(); return super.send(spanBytes); } HttpCollectorClient(String endpoint, Map<String, String> headers); HttpCollectorClient(String endpoint); HttpCollectorClient(final String endpoint, final Map<String, String> headers, final CloseableHttpClient httpClient); @Override boolean send(Span span); }### Answer: @Test public void testDispatch() throws Exception { final Span span = tracer.buildSpan("happy-path").asChildOf(spanContext).start(); span.finish(); final ArgumentCaptor<HttpPost> httpPostCapture = ArgumentCaptor.forClass(HttpPost.class); final CloseableHttpClient http = Mockito.mock(CloseableHttpClient.class); final CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class); final BasicStatusLine statusLine = new BasicStatusLine(new ProtocolVersion("v", 1, 1), 200, ""); when(http.execute(httpPostCapture.capture())).thenReturn(httpResponse); when(httpResponse.getStatusLine()).thenReturn(statusLine); final Map<String, String> headers = new HashMap<>(); headers.put("client-id", "my-client"); final HttpCollectorClient client = new HttpCollectorClient("http: final boolean isSuccess = client.send(span); client.close(); verify(http, times(1)).execute(httpPostCapture.capture()); verify(httpResponse, times(1)).close(); verify(http, times(1)).close(); verifyCapturedHttpPost(httpPostCapture.getValue()); assertEquals(isSuccess, true); } @Test(expected = ClientException.class) public void testFailedDispatch() throws Exception { final Span span = tracer.buildSpan("sad-path").start(); span.finish(); final ArgumentCaptor<HttpPost> httpPostCapture = ArgumentCaptor.forClass(HttpPost.class); final CloseableHttpClient http = Mockito.mock(CloseableHttpClient.class); final CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class); final BasicStatusLine statusLine = new BasicStatusLine(new ProtocolVersion("v", 1, 1), 404, ""); when(http.execute(httpPostCapture.capture())).thenReturn(httpResponse); when(httpResponse.getStatusLine()).thenReturn(statusLine); final HttpCollectorClient client = new HttpCollectorClient("http: client.send(span); } @Test(expected = ClientException.class) public void testAnotherFailedDispatch() throws Exception { final Span span = tracer.buildSpan("sad-path").start(); span.finish(); final ArgumentCaptor<HttpPost> httpPostCapture = ArgumentCaptor.forClass(HttpPost.class); final CloseableHttpClient http = Mockito.mock(CloseableHttpClient.class); when(http.execute(httpPostCapture.capture())).thenThrow(new IOException()); final HttpCollectorClient client = new HttpCollectorClient("http: client.send(span); }
### Question: RemoteDispatcher implements Dispatcher { @Override public void dispatch(Span span) { try (Sample timer = dispatchTimer.start()) { if (running.get()) { final boolean accepted = acceptQueue.offer(span); if (!accepted) { dispatchRejectedCounter.increment(); LOGGER.warn("Send queue is rejecting new spans"); } } else { dispatchRejectedCounter.increment(); LOGGER.warn("Dispatcher is shutting down and queue is now rejecting new spans"); } } } RemoteDispatcher(Metrics metrics, Client client, BlockingQueue<Span> queue, long flushInterval, long shutdownTimeout, ScheduledExecutorService executor); @Override String toString(); @Override void dispatch(Span span); @Override void close(); @Override void flush(); }### Answer: @Test public void testFlushTimer() { Span span = tracer.buildSpan("happy-path").start(); dispatcher.dispatch(span); Awaitility.await() .atMost(flushInterval * 2, TimeUnit.MILLISECONDS) .until(() -> client.getFlushedSpans().size() > 0); Assert.assertEquals(0, client.getReceivedSpans().size()); Assert.assertEquals(1, client.getFlushedSpans().size()); Assert.assertEquals(1, client.getTotalSpans().size()); }
### Question: Span implements io.opentracing.Span { public String getServiceName() { synchronized (this) { return getTracer().getServiceName(); } } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString(); @Override void finish(); @Override void finish(long finishMicros); Long getDuration(); Long getStartTime(); Tracer getTracer(); @Override SpanContext context(); String getServiceName(); String getOperationName(); @Override Span setOperationName(String operationName); @Override Span setBaggageItem(String key, String value); @Override String getBaggageItem(String key); Map<String, String> getBaggageItems(); @Override Span setTag(String key, Number value); @Override io.opentracing.Span setTag(Tag<T> tag, T value); @Override Span setTag(String key, boolean value); @Override Span setTag(String key, String value); Map<String, Object> getTags(); @Override Span log(long timestampMicroseconds, Map<String, ?> fields); @Override Span log(long timestampMicroseconds, String event); @Override Span log(Map<String, ?> fields); @Override Span log(String event); List<LogData> getLogs(); }### Answer: @Test public void testServiceName() { String expected = "service-name"; Span span = new Tracer.Builder(metrics, expected, dispatcher).build().buildSpan(expected).start(); Assert.assertEquals(expected, span.getServiceName()); }
### Question: Span implements io.opentracing.Span { public Map<String, Object> getTags() { synchronized (this) { return Collections.unmodifiableMap(tags); } } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString(); @Override void finish(); @Override void finish(long finishMicros); Long getDuration(); Long getStartTime(); Tracer getTracer(); @Override SpanContext context(); String getServiceName(); String getOperationName(); @Override Span setOperationName(String operationName); @Override Span setBaggageItem(String key, String value); @Override String getBaggageItem(String key); Map<String, String> getBaggageItems(); @Override Span setTag(String key, Number value); @Override io.opentracing.Span setTag(Tag<T> tag, T value); @Override Span setTag(String key, boolean value); @Override Span setTag(String key, String value); Map<String, Object> getTags(); @Override Span log(long timestampMicroseconds, Map<String, ?> fields); @Override Span log(long timestampMicroseconds, String event); @Override Span log(Map<String, ?> fields); @Override Span log(String event); List<LogData> getLogs(); }### Answer: @Test public void testTagForTagType() { String key = "typed-key-name"; String value = "typed-tag-value-value"; StringTag stringTag = new StringTag(key); stringTag.set(span, value); Assert.assertEquals(value, span.getTags().get(key)); }
### Question: TeamUserController { @ApiOperation(value = "This API returns all TeamUser Objects present in Elastic Search", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned all TeamUser Objects"), @ApiResponse(code = 401, message = "User is not authorized to view requested object"), @ApiResponse(code = 404, message = "No TeamUser object found") }) @RequestMapping(value = "/api/users/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getAllUsers() { logger.debug("Fetching All Users "); List<TeamUser> userList = Lists.newArrayList(userDetailsService.findAll()); if (userList == null || userList.isEmpty()) { final String error = " No User Found in TeamUser repository"; logger.debug(error); final MessageWrapper apiError = new MessageWrapper(HttpStatus.NOT_FOUND, error, error); return new ResponseEntity<>(apiError, new HttpHeaders(), apiError.getStatus()); } return new ResponseEntity<>(userList, HttpStatus.OK); } @ApiOperation(value = "This API returns all TeamUser Objects present in Elastic Search", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned all TeamUser Objects"), @ApiResponse(code = 401, message = "User is not authorized to view requested object"), @ApiResponse(code = 404, message = "No TeamUser object found") }) @RequestMapping(value = "/api/users/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Object> getAllUsers(); @ApiOperation(value = "This API returns TeamUser Object present in Elastic Search for current user", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned TeamUser Object for current user"), @ApiResponse(code = 401, message = "User is not authorized to view requested object"), @ApiResponse(code = 404, message = "No TeamUser object found for current user") }) @RequestMapping(value = "/api/user/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Object> getCurrentTeamOfUser(HttpServletRequest request); @ApiOperation(value = "This API updates TeamUser Objects into Elastic Search for current user", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "TeamUser objects successfully updated into ES for current user"), @ApiResponse(code = 401, message = "User is not authorized to perform Update operation"), @ApiResponse(code = 404, message = "TeamUser object not found in ES for current user"), @ApiResponse(code = 400, message = "Input Request object is not valid") }) @RequestMapping(value = "/api/user/{newteamname}", method = RequestMethod.PUT, produces = "application/json") ResponseEntity<Object> updateTeamOfUser(HttpServletRequest request, @PathVariable("newteamname") String newteamname); }### Answer: @Test public void testGetAllUsers() { TeamUser teamUser = createTeamUserObject(USERNAME, TEAMNAME); List<TeamUser> teamUserList = new ArrayList<>(); teamUserList.add(teamUser); when(teamUserRepository.findAll()).thenReturn(teamUserList); @SuppressWarnings("unchecked") List<TeamUser> getAllUsers = (List<TeamUser>) teamUserController.getAllUsers().getBody(); assertEquals(1, getAllUsers.size()); assertEquals(USERNAME, getAllUsers.get(0).getUserName()); assertEquals(TEAMNAME, getAllUsers.get(0).getTeamName()); } @Test public void testGetAllUsersErrCndtn() { List<TeamUser> teamUserList = new ArrayList<>(); when(teamUserRepository.findAll()).thenReturn(teamUserList); MessageWrapper apiError = (MessageWrapper) teamUserController.getAllUsers().getBody(); assertEquals(HttpStatus.NOT_FOUND, apiError.getStatus()); assertEquals(" No User Found in TeamUser repository", apiError.getStatusMessage()); }
### Question: TeamUserController { @ApiOperation(value = "This API returns TeamUser Object present in Elastic Search for current user", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned TeamUser Object for current user"), @ApiResponse(code = 401, message = "User is not authorized to view requested object"), @ApiResponse(code = 404, message = "No TeamUser object found for current user") }) @RequestMapping(value = "/api/user/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getCurrentTeamOfUser(HttpServletRequest request) { logger.debug("Fetching Current Team for user name."); TeamUser teamUser = userDetailsService.getCurrentTeamForUser(request); if (teamUser == null) { final String error = "TeamUser Not found for a User."; logger.debug(error); final MessageWrapper apiError = new MessageWrapper(HttpStatus.NOT_FOUND, error, error); return new ResponseEntity<>(apiError, new HttpHeaders(), apiError.getStatus()); } return new ResponseEntity<>(teamUser, HttpStatus.OK); } @ApiOperation(value = "This API returns all TeamUser Objects present in Elastic Search", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned all TeamUser Objects"), @ApiResponse(code = 401, message = "User is not authorized to view requested object"), @ApiResponse(code = 404, message = "No TeamUser object found") }) @RequestMapping(value = "/api/users/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Object> getAllUsers(); @ApiOperation(value = "This API returns TeamUser Object present in Elastic Search for current user", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned TeamUser Object for current user"), @ApiResponse(code = 401, message = "User is not authorized to view requested object"), @ApiResponse(code = 404, message = "No TeamUser object found for current user") }) @RequestMapping(value = "/api/user/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Object> getCurrentTeamOfUser(HttpServletRequest request); @ApiOperation(value = "This API updates TeamUser Objects into Elastic Search for current user", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "TeamUser objects successfully updated into ES for current user"), @ApiResponse(code = 401, message = "User is not authorized to perform Update operation"), @ApiResponse(code = 404, message = "TeamUser object not found in ES for current user"), @ApiResponse(code = 400, message = "Input Request object is not valid") }) @RequestMapping(value = "/api/user/{newteamname}", method = RequestMethod.PUT, produces = "application/json") ResponseEntity<Object> updateTeamOfUser(HttpServletRequest request, @PathVariable("newteamname") String newteamname); }### Answer: @Test public void testGetCurrentTeamOfUser() { setSecuirtyContext(TEAMNAME, USERNAME); TeamUser teamUser = createTeamUserObject(USERNAME, TEAMNAME); when(teamUserRepository.findByUserNameAndDefaultFlag(USERNAME, "Y")).thenReturn(teamUser); TeamUser user = (TeamUser) teamUserController.getCurrentTeamOfUser(req).getBody(); assertEquals(USERNAME, user.getUserName()); assertEquals(TEAMNAME, user.getTeamName()); assertEquals(ROLE, user.getRoles()); } @Test public void testGetCurrentTeamOfUserErrCndtn() { setSecuirtyContext(TEAMNAME, USERNAME); when(teamUserRepository.findByUserNameAndDefaultFlag(USERNAME, "Y")).thenReturn(null); MessageWrapper apiError = (MessageWrapper) teamUserController.getCurrentTeamOfUser(req).getBody(); assertEquals(HttpStatus.NOT_FOUND, apiError.getStatus()); assertEquals("TeamUser Not found for a User.", apiError.getStatusMessage()); }
### Question: Customer extends Person { public void setEmail(String email) { this.email = email; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); Integer getAge(); void setAge(Integer age); }### Answer: @Test public void shouldShowDifferentLifeCyclePhases() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565"); assertFalse(em.contains(customer)); System.out.println("\nPERSIST"); tx.begin(); em.persist(customer); tx.commit(); assertTrue(em.contains(customer), "should be in the persistence context after persisting"); System.out.println("\nFIND"); em.clear(); assertFalse(em.contains(customer), "should not be in the persistence context after clearing"); customer = em.find(Customer.class, customer.getId()); assertTrue(em.contains(customer), "should be in the persistence context after finding"); System.out.println("\nDETACH"); em.detach(customer); assertFalse(em.contains(customer), "should not be in the persistence context after detaching"); customer = em.find(Customer.class, customer.getId()); assertTrue(em.contains(customer), "should be in the persistence context after finding"); System.out.println("\nREFRESH"); customer.setEmail("[email protected]"); tx.begin(); em.refresh(customer); tx.commit(); assertTrue(em.contains(customer), "should be in the persistence context after refreshing"); System.out.println("\nSET"); tx.begin(); customer.setFirstName("new first name"); customer.setFirstName("new last name"); tx.commit(); System.out.println("\nMERGE"); em.clear(); assertFalse(em.contains(customer), "should not be in the persistence context after clearing"); customer.setEmail("[email protected]"); tx.begin(); customer = em.merge(customer); tx.commit(); assertTrue(em.contains(customer), "should be in the persistence context after merging"); System.out.println("\nREMOVE"); tx.begin(); em.remove(customer); tx.commit(); assertFalse(em.contains(customer), "should not be in the persistence context after removing"); }
### Question: Item { public Long getId() { return id; } Item(); Item(String title, Float price, String description); Long getId(); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); }### Answer: @Test public void shouldCreateSeveralItems() throws Exception { Item item = new Item("Junk", 52.50f, "A piece of junk"); CD cd01 = new CD("St Pepper", 12.80f, "Beatles master piece", "Apple", 1, 53.32f, "Pop/Rock"); CD cd02 = new CD("Love SUpreme", 20f, "John Coltrane love moment", "Blue Note", 2, 87.45f, "Jazz"); Book book01 = new Book("H2G2", 21f, "Best IT book", "123-456-789", "Pinguin", 321, false); Book book02 = new Book("The Robots of Dawn", 37.5f, "Robots, again and again", "0-553-29949-2 ", "Foundation", 264, true); tx.begin(); em.persist(item); em.persist(cd01); em.persist(cd02); em.persist(book01); em.persist(book02); tx.commit(); assertNotNull(item.getId(), "Item Id should not be null"); assertNotNull(cd01.getId(), "CD1 Id should not be null"); assertNotNull(cd02.getId(), "CD2 Id should not be null"); assertNotNull(book01.getId(), "Book1 Id should not be null"); assertNotNull(book02.getId(), "Book2 Id should not be null"); }
### Question: CreditCard { public String getNumber() { return number; } CreditCard(); CreditCard(String number, String expiryDate, Integer controlNumber, CreditCardType creditCardType); String getNumber(); void setNumber(String number); String getExpiryDate(); void setExpiryDate(String expiryDate); Integer getControlNumber(); void setControlNumber(Integer controlNumber); CreditCardType getType(); void setType(CreditCardType creditCardType); }### Answer: @Test public void shouldCreateACreditCard() throws Exception { CreditCard creditCard = new CreditCard("123412341234", "12/12", 1253, AMERICAN_EXPRESS); tx.begin(); em.persist(creditCard); tx.commit(); assertNotNull(creditCard.getNumber(), "Id should not be null"); String dbCreditCardType = (String) em.createNativeQuery("select creditCardType from CreditCard where number = '123412341234'").getSingleResult(); assertEquals("A", dbCreditCardType, "Should be A for American Express"); } @Test public void shouldCreateACreditCard() throws Exception { CreditCard creditCard = new CreditCard("123412341234", "12/12", 1253, CreditCardType.AMERICAN_EXPRESS); tx.begin(); em.persist(creditCard); tx.commit(); assertNotNull(creditCard.getNumber(), "Id should not be null"); }
### Question: Address { public Long getId() { return id; } Address(); Address(Long id, String street1, String street2, String city, String state, String zipcode, String country); Long getId(); void setId(Long id); String getStreet1(); void setStreet1(String street1); String getStreet2(); void setStreet2(String street2); String getCity(); void setCity(String city); String getState(); void setState(String state); String getZipcode(); void setZipcode(String zipcode); String getCountry(); void setCountry(String country); }### Answer: @Test public void shouldCreateAnAddress() throws Exception { Address address = new Address(getRandomId(), "65B Ritherdon Rd", "At James place", "London", "LDN", "7QE554", "UK"); tx.begin(); em.persist(address); tx.commit(); assertNotNull(address.getId(), "Id should not be null"); }
### Question: Book { public Long getId() { return id; } Book(); Book(Long id, String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); void setId(Long id); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); String getIsbn(); void setIsbn(String isbn); Integer getNbOfPages(); void setNbOfPages(Integer nbOfPages); Boolean getIllustrations(); void setIllustrations(Boolean illustrations); }### Answer: @Test public void shouldCreateABook() throws Exception { Book book = new Book(getRandomId(), "The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); }
### Question: Book { public Long getId() { return id; } Book(); Book(String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); void setId(Long id); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); String getIsbn(); void setIsbn(String isbn); Integer getNbOfPages(); void setNbOfPages(Integer nbOfPages); Boolean getIllustrations(); void setIllustrations(Boolean illustrations); }### Answer: @Test public void shouldCreateABook() throws Exception { Book book = new Book("The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); }
### Question: News { public String getContent() { return content; } News(); News(NewsId id, String content); NewsId getId(); void setId(NewsId id); String getContent(); void setContent(String content); }### Answer: @Test public void shouldCreateANews() throws Exception { News news = new News(new NewsId("Richard Wright has died", "EN"), "The keyboard of Pink Floyd has died today"); tx.begin(); em.persist(news); tx.commit(); news = em.find(News.class, new NewsId("Richard Wright has died", "EN")); assertEquals("The keyboard of Pink Floyd has died today", news.getContent()); }
### Question: AddressEndpoint { @PostMapping("/addresses") public Address createAddress(@RequestBody Address address) { return addressRepository.save(address); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address address); @GetMapping(value = "/addresses/count") Long countAll(); @GetMapping(value = "/addresses/country/{country}") List<Address> getAddressesByCountry(@PathVariable String country); @GetMapping(value = "/addresses/like/{zip}") List<Address> getAddressesLikeZip(@PathVariable String zip); }### Answer: @Test @Transactional public void createAddress() throws Exception { mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string(ALL_ADDRESSES)); Address address = new Address().street1("233 Spring Street").city("New York").state("NY").zipcode("12345").country("USA"); mockAddressEndpoint.perform(post("/addresses") .contentType("application/json") .content(convertObjectToJsonBytes(address))) .andExpect(status().isOk()); mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string("8")); }
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber, Date dateOfBirth, Date creationDate); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); Date getDateOfBirth(); void setDateOfBirth(Date dateOfBirth); Date getCreationDate(); void setCreationDate(Date creationDate); }### Answer: @Test public void shoulCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565", new Date(), new Date()); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); }
### Question: BookService { public void createBook() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("cdbookstorePU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Book book = new Book().title("H2G2").price(12.5F).isbn("1-84023-742-2").nbOfPages(354); tx.begin(); em.persist(book); tx.commit(); em.close(); emf.close(); } void createBook(); }### Answer: @Test void shouldCreateABook() { BookService bookService = new BookService(); bookService.createBook(); }
### Question: Customer { public void setAddress(Address address) { this.address = address; } Customer(); Customer(String firstName, String lastName, String email); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); Address getAddress(); void setAddress(Address address); }### Answer: @Test public void shouldPersistWithFlush() throws Exception { Customer customer = new Customer("Anthony", "Balla", "[email protected]"); Address address = new Address("Ritherdon Rd", "London", "8QE", "UK"); customer.setAddress(address); assertThrows(IllegalStateException.class, () -> { tx.begin(); em.persist(customer); em.flush(); em.persist(address); tx.commit(); }); }
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); Address getAddress(); void setAddress(Address address); }### Answer: @Test public void shouldPersistACustomer() throws Exception { Customer customer = new Customer("Anthony", "Balla", "[email protected]"); tx.begin(); em.persist(customer); tx.commit(); assertNotNull(customer.getId()); } @Test public void shouldPersistAnAddress() throws Exception { Address address = new Address("Ritherdon Rd", "London", "8QE", "UK"); tx.begin(); em.persist(address); tx.commit(); assertNotNull(address.getId()); } @Test public void shouldPersistACustomerTwice() throws Exception { Customer customer = new Customer("Anthony", "Balla", "[email protected]"); tx.begin(); em.persist(customer); tx.commit(); assertNotNull(customer.getId()); em.clear(); assertThrows(RollbackException.class, () -> { tx.begin(); em.persist(customer); tx.commit(); }); }
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); void setPhoneNumber(String phoneNumber); @Access(AccessType.PROPERTY) @Column(name = "phone_number", length = 555) String getPhoneNumber(); }### Answer: @Test public void shouldCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565"); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); }
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); }### Answer: @Test public void shouldCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565"); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); }
### Question: Customer { @Id @GeneratedValue public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); void setId(Long id); void setFirstName(String firstName); void setLastName(String lastName); void setEmail(String email); void setPhoneNumber(String phoneNumber); @Id @GeneratedValue Long getId(); @Column(name = "first_name", nullable = false, length = 50) String getFirstName(); @Column(name = "last_name", nullable = false, length = 50) String getLastName(); String getEmail(); @Column(name = "phone_number", length = 15) String getPhoneNumber(); }### Answer: @Test public void shouldCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565"); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); }
### Question: AddressEndpoint { @GetMapping(value = "/addresses/country/{country}") public List<Address> getAddressesByCountry(@PathVariable String country) { return addressRepository.findAllByCountry(country); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address address); @GetMapping(value = "/addresses/count") Long countAll(); @GetMapping(value = "/addresses/country/{country}") List<Address> getAddressesByCountry(@PathVariable String country); @GetMapping(value = "/addresses/like/{zip}") List<Address> getAddressesLikeZip(@PathVariable String zip); }### Answer: @Test @Transactional public void getAddressesByCountry() throws Exception { mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string(ALL_ADDRESSES)); mockAddressEndpoint.perform(get("/addresses/country/AU")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].country").isArray()); mockAddressEndpoint.perform(get("/addresses/country/dummy")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].country").isEmpty()); }
### Question: Author { public Author firstName(String firstName) { this.firstName = firstName; return this; } Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); Author firstName(String firstName); String getLastName(); void setLastName(String lastName); Author lastName(String lastName); String getBio(); void setBio(String bio); Author surnbioame(String bio); String getEmail(); void setEmail(String email); Author email(String email); }### Answer: @Test void shouldNotCreateAnAuthorWithNullFirstname() { Author author = new Author().firstName(null); tx.begin(); em.persist(author); assertThrows(RollbackException.class, () -> tx.commit()); }
### Question: AddressEndpoint { @GetMapping(value = "/addresses/like/{zip}") public List<Address> getAddressesLikeZip(@PathVariable String zip) { return addressRepository.findAllLikeZip(zip); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address address); @GetMapping(value = "/addresses/count") Long countAll(); @GetMapping(value = "/addresses/country/{country}") List<Address> getAddressesByCountry(@PathVariable String country); @GetMapping(value = "/addresses/like/{zip}") List<Address> getAddressesLikeZip(@PathVariable String zip); }### Answer: @Test @Transactional public void getAddressesLikeZip() throws Exception { mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string(ALL_ADDRESSES)); mockAddressEndpoint.perform(get("/addresses/like/8QE")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").value("8QE")); mockAddressEndpoint.perform(get("/addresses/like/Q")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").value("8QE")); mockAddressEndpoint.perform(get("/addresses/like/E")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").isArray()); mockAddressEndpoint.perform(get("/addresses/like/dummy")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").isEmpty()); }
### Question: Artist { public Artist firstName(String firstName) { this.firstName = firstName; return this; } Artist(); Artist(String firstName, String lastName, String email, String bio, LocalDate dateOfBirth); Long getId(); String getFirstName(); void setFirstName(String firstName); Artist firstName(String firstName); String getLastName(); void setLastName(String lastName); Artist lastName(String lastName); String getEmail(); void setEmail(String email); Artist email(String email); String getBio(); void setBio(String bio); Artist bio(String bio); LocalDate getDateOfBirth(); void setDateOfBirth(LocalDate dateOfBirth); Artist dateOfBirth(LocalDate dateOfBirth); @Override String toString(); }### Answer: @Test void shouldNotCreateAnArtistWithNullFirstname() { Artist artist = new Artist().firstName(null); tx.begin(); em.persist(artist); assertThrows(RollbackException.class, () -> tx.commit()); }
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber, LocalDate dateOfBirth, LocalDateTime creationDate); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); LocalDate getDateOfBirth(); void setDateOfBirth(LocalDate dateOfBirth); Integer getAge(); void setAge(Integer age); LocalDateTime getCreationDate(); void setCreationDate(LocalDateTime creationDate); }### Answer: @Test public void shoulCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565", LocalDate.now(), LocalDateTime.now()); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); }
### Question: Book { public Long getId() { return id; } Book(); Book(String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); String getIsbn(); void setIsbn(String isbn); Integer getNbOfPages(); void setNbOfPages(Integer nbOfPages); Boolean getIllustrations(); void setIllustrations(Boolean illustrations); }### Answer: @Test public void shouldCreateABook() throws Exception { Book book = new Book("The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); }
### Question: Track { public Long getId() { return id; } Track(); Track(String title, Float duration, String description); Long getId(); String getTitle(); void setTitle(String title); Float getDuration(); void setDuration(Float duration); byte[] getWav(); void setWav(byte[] wav); String getDescription(); void setDescription(String description); }### Answer: @Test public void shouldCreateATrack() throws Exception { Track track = new Track("Sgt Pepper Lonely Heart Club Ban", 4.53f, "Listen to the trumpet carefully, it's George Harrison playing"); tx.begin(); em.persist(track); tx.commit(); assertNotNull(track.getId(), "Id should not be null"); }
### Question: News { public String getTitle() { return title; } News(); News(String title, String language, String content); String getTitle(); void setTitle(String title); String getLanguage(); void setLanguage(String language); String getContent(); void setContent(String content); }### Answer: @Test public void shouldCreateANews() throws Exception { News news = new News("Richard Wright has died", "EN", "The keyboard of Pink Floyd has died today"); tx.begin(); em.persist(news); tx.commit(); assertNotNull(news.getTitle(), "Id should not be null"); }
### Question: NamedExtension implements Extension<T> { @Override public String getKey() { return key; } NamedExtension(String key); @Override String getKey(); @Override boolean equals(Object o); boolean equals(NamedExtension<?> o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void named_extensions_returns_its_own_key() { assertEquals("my.extension", Extension.key("my.extension").getKey()); } @Test(expected = UnsupportedOperationException.class) public void anonymous_throws_if_try_to_get_the_key() { Extension.anonymous().getKey(); }
### Question: LocalRrCache implements Storage, Debuggable { @Override public List<Integer> getCacheIds() { List<Integer> ids = new ArrayList<>(); for (CacheElement cacheElement : cacheStorage) { if (cacheElement != null) { ids.add(cacheElement.getId()); } } return ids; } LocalRrCache(Storage backendStore, int cacheSize); @Override boolean store(int id, String value); @Override String load(int id); @Override ClusterStatus getCurrentClusterStatus(); @Override boolean getCurrentNodeStatus(InetAddress ia); @Override List<Integer> getCacheIds(); }### Answer: @Test public void testStorage() { storeAndLoad(1000); storeAndLoad(1001); storeAndLoad(1002); Assertions.assertEquals(Arrays.asList(1000, 1001, 1002), localRrCache.getCacheIds()); storeAndLoad(1003); storeAndLoad(1004); Assertions.assertEquals(Arrays.asList(1000, 1001, 1002, 1003, 1004), localRrCache.getCacheIds()); for (int i = 1000; i < 1010; i++) { storeAndLoad(i); } }
### Question: Part02Transform { public Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress) { return Mono.zip(phoneNumber, deliveryAddress, (p, d) -> new Order(p, d)); } Flux<Tuple2<String, Integer>> pairValues(Flux<String> flux1, Flux<Integer> flux2); Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress); }### Answer: @Test public void combineValues() { Mono<String> phoneNumber = Mono.just("076123456"); Mono<String> deliveryAddress = Mono.just("Paradeplatz Zurich"); Mono<Order> order = workshop.combineValues(phoneNumber, deliveryAddress); StepVerifier.create(order).expectNext(new Order("076123456", "Paradeplatz Zurich")); order = workshop.combineValues(Mono.empty(), deliveryAddress); StepVerifier.create(order).verifyComplete(); order = workshop.combineValues(Mono.error(new RuntimeException()), deliveryAddress); StepVerifier.create(order).verifyError(); }
### Question: Part03Filtering { Flux<Integer> filterEven(Flux<Integer> flux) { return flux.filter(i -> i % 2 == 0).log(); } }### Answer: @Test public void filterEven() { Flux<Integer> flux = workshop.filterEven(Flux.just(1, 2, 3, 4, 5)); StepVerifier.create(flux) .expectNext(2, 4) .verifyComplete(); }
### Question: Part03Filtering { Flux<Integer> ignoreDuplicates(Flux<Integer> flux) { return flux.distinct().log(); } }### Answer: @Test public void ignoreDuplicates() { Flux<Integer> flux = workshop.ignoreDuplicates(Flux.just(1, 1, 2, 2, 3, 4)); StepVerifier.create(flux) .expectNext(1, 2, 3, 4) .verifyComplete(); }
### Question: Part03Filtering { Mono<Integer> emitLast(Flux<Integer> flux) { return flux.last(100).log(); } }### Answer: @Test public void takeAtMostOne() { Mono<Integer> mono = workshop.emitLast(Flux.just(51, 61, 12)); StepVerifier.create(mono) .expectNext(12) .verifyComplete(); mono = workshop.emitLast(Flux.empty()); StepVerifier.create(mono).expectNext(100).verifyComplete(); }
### Question: Part03Filtering { Flux<Integer> ignoreUntil(Flux<Integer> flux) { return flux.skipUntil(integer -> integer > 10).log(); } }### Answer: @Test public void ignoreUntil() { Flux<Integer> flux = workshop.ignoreUntil(Flux.just(1, 3, 15, 5, 10)); StepVerifier.create(flux) .expectNext(15, 5, 10) .verifyComplete(); StepVerifier.create(workshop.ignoreUntil(Flux.just(1, 3, 5))).verifyComplete(); StepVerifier.create(workshop.ignoreUntil(Flux.empty())).verifyComplete(); }
### Question: Part03Filtering { Mono<Integer> expectAtMostOneOrEmpty(Flux<Integer> flux) { return flux.singleOrEmpty().log(); } }### Answer: @Test public void expectAtMostOneOrEmpty() { Mono<Integer> mono = workshop.expectAtMostOneOrEmpty(Flux.just(1, 2, 3)); StepVerifier.create(mono) .expectError() .verify(); StepVerifier.create(Flux.just(1)).expectNext(1).verifyComplete(); StepVerifier.create(Flux.empty()).verifyComplete(); }
### Question: Part03Filtering { Mono<Boolean> asyncFilter(Integer integer) { return Mono.just(integer % 2 == 0).delayElement(Duration.ofMillis(500)); } }### Answer: @Test public void asyncFilter() { Flux<Integer> flux = workshop.asyncComputedFilter(Flux.just(1, 2, 3, 4, 5)); StepVerifier.create(flux) .expectNext(2, 4) .verifyComplete(); }
### Question: MaxSubProblem { public int maxSub(int[] data) { int maxend = data[0]; int maxfar = data[0]; for (int i = 1; i < data.length; i++) { maxend = Math.max(data[i], maxend + data[i]); maxfar = Math.max(maxfar, maxend); } return maxfar > 0 ? maxfar : 0; } int maxSub1(int[] data); int maxSub2(int[] data); int maxSub(int[] data); }### Answer: @Test public void testShortNegativeArray() { int[] numbers = new int[]{-12}; assertEquals(0, ms.maxSub(numbers)); } @Test public void testAllNegative() { int[] numbers = new int[]{-31, -59, -26, -13, -47}; assertEquals(0, ms.maxSub(numbers)); } @Test public void test1() { int[] numbers = new int[]{1, 3, -5, 3, 3, 2, -9, -2}; assertEquals(8, ms.maxSub(numbers)); } @Test public void test2() { int[] numbers = new int[]{31, -41, 59, 26, -53, 58, 97, -93, -23}; assertEquals(187, ms.maxSub(numbers)); } @Test public void testGlobalMaxBeforeMin() { int[] numbers = new int[]{31, -41, 259, 26, -453, 58, 97, -93, -23}; assertEquals(285, ms.maxSub(numbers)); } @Test public void testMaxSeqStartingAt0() { int[] numbers = new int[]{41, -31, 59, -97, -53, -58, 26}; assertEquals(69, ms.maxSub(numbers)); } @Test public void testMaxSeqEndingAtEnd() { int[] numbers = new int[]{31, -41, 59, 26, -53, 58, 97}; assertEquals(187, ms.maxSub(numbers)); } @Test public void testOneStepMax() { int[] numbers = new int[]{2, -10, 8, -10, 2}; assertEquals(8, ms.maxSub(numbers)); } @Test public void testOneStepMaxAt0() { int[] numbers = new int[]{41, -31, -59, -26, -13}; assertEquals(41, ms.maxSub(numbers)); } @Test public void testOneStepMaxAtEnd() { int[] numbers = new int[]{-31, -59, -26, -13, 47}; assertEquals(47, ms.maxSub(numbers)); } @Test public void testShortArray() { int[] numbers = new int[]{12}; assertEquals(12, ms.maxSub(numbers)); }
### Question: SimpleArrayList extends AbstractList<E> implements List<E> { @Override public void add(int index, E element) { if (index < 0 || index > size()) { throw new IndexOutOfBoundsException("Invalid index"); } if (arr.length == size) { Object[] temparr = new Object[size * 2]; for (int i = 0; i < size; i++) { counter += 2; temparr[i] = arr[i]; } arr = temparr; } for (int i = size; i > index; i--) { counter += 2; arr[i] = arr[i - 1]; } counter++; arr[index] = element; size++; } @Override int size(); @SuppressWarnings("unchecked") @Override E get(int index); @Override E set(int index, E element); @Override void add(int index, E element); @Override E remove(int index); long getCounter(); }### Answer: @Test public void testIndexAdd_WithoutEnlarge() { int[] numbers = new int[]{1, 4, 6, 7}; for (int i = numbers.length - 1; i >= 0; i--) { list.add(0, numbers[i]); } assertListValues(numbers); } @Test(expected = IndexOutOfBoundsException.class) public void testAddOnNegativIndex_ExpectException() { list.add(-1, 2); fail("Exception was expected"); } @Test(expected = IndexOutOfBoundsException.class) public void testAddOnHugeTooLargeIndex_ExpectException() { list.add(0, 1); list.add(44444, 2); fail("Exception was expected"); } @Test(expected = IndexOutOfBoundsException.class) public void testAddOnSmallTooLargeIndex_ExpectException() { list.add(0, 1); list.add(2, 2); fail("Exception was expected"); } @Test public void testAddWithEnlarge() { int[] numbers = new int[1000]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i; list.add(i, i); } assertListValues(numbers); } @Test public void testAddWithEnlargeReverse() { int[] numbers = new int[1000]; for (int i = numbers.length - 1; i >= 0; i--) { numbers[i] = i; list.add(0, i); } assertListValues(numbers); } @Test public void testAddAnywhere() { int[] numbers = {10, 21, 11, 22, 12, 23, 13, 24, 14, 25, 15, 26, 16, 27, 17, 28, 0, 29, 1, 30, 2, 31, 3, 32, 4, 33, 5, 34, 6, 35, 7, 36}; for (int i = 0; i < 8; i++) list.add(i); for (int i = 0; i < 8; i++) list.add(i, 10 + i); for (int i = 16; i > 0; i--) list.add(i, 20 + i); assertListValues(numbers); } @Test public void addNullValue() { list.add(null); }
### Question: SimpleArrayList extends AbstractList<E> implements List<E> { @Override public E remove(int index) { E old = get(index); while (index + 1 < size) { counter += 2; arr[index] = arr[index + 1]; index++; } counter++; arr[size] = null; size--; return old; } @Override int size(); @SuppressWarnings("unchecked") @Override E get(int index); @Override E set(int index, E element); @Override void add(int index, E element); @Override E remove(int index); long getCounter(); }### Answer: @Test public void testRemove() { int[] numbers = new int[10]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i; list.add(i, i); } assertListValues(numbers); list.remove(1); list.remove(0); int[] remainingNumbers = Arrays.copyOfRange(numbers, 2, numbers.length); assertListValues(remainingNumbers); }
### Question: BinSearchFirstElement { public static int binSearch(int[] data, int value) { int l = -1, h = data.length; while (l + 1 != h) { int m = l + (h - l) / 2; if (data[m] < value) { l = m; } else { h = m; } } return h; } static int binSearch(int[] data, int value); }### Answer: @Test public void findFirstElement() { int[] numbers = new int[] { 1, 2, 3, 3, 3, 3, 3, 4, 5 }; int index = BinSearchFirstElement.binSearch(numbers, 3); assertEquals(2, index); } @Test public void findFirstElementFirstHalf() { int[] numbers = new int[] { 1, 2, 2, 3, 3, 3, 3, 3, 4, 5 }; int index = BinSearchFirstElement.binSearch(numbers, 2); assertEquals(1, index); } @Test public void findFirstElementSecondHalf() { int[] numbers = new int[] { 1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5 }; int index = BinSearchFirstElement.binSearch(numbers, 4); assertEquals(8, index); } @Test public void testAllElementsEqual() { int[] numbers = new int[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; int index = BinSearchFirstElement.binSearch(numbers, 3); assertEquals(0, index); } @Test public void testNoFirstElement() { int[] numbers = new int[] { 1, 2, 3, 3, 3, 3, 3, 8, 9 }; int index = BinSearchFirstElement.binSearch(numbers, 5); assertEquals(7, index); } @Test public void testTooSmallElement() { int[] numbers = new int[] { 1, 2, 3, 3, 3, 3, 3, 8, 9 }; int index = BinSearchFirstElement.binSearch(numbers, 0); assertEquals(0, index); } @Test public void testTooLargeElement() { int[] numbers = new int[] { 1, 2, 3, 3, 3, 3, 3, 8, 9 }; int index = BinSearchFirstElement.binSearch(numbers, 11); assertEquals(9, index); }
### Question: BinaryObjectSearch { public static <T extends Comparable<? super T>> int binSearch(T[] data, T value) { int l = -1, h = data.length; while (l + 1 != h) { int m = l + (h - l) / 2; int compare = data[m].compareTo(value); if (compare < 0) { l = m; } else if (compare > 0) { h = m; } else { return m; } } return NOT_FOUND; } static int binSearch(T[] data, T value); static final int NOT_FOUND; }### Answer: @Test public void testExistingIntegerAtStart() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 1); assertEquals(0, index); } @Test public void testExistingIntegerInBetween1() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 3); assertEquals(1, index); } @Test public void testExistingIntegerInBetween2() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 4); assertEquals(2, index); } @Test public void testExistingIntegerInBetween3() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 5); assertEquals(3, index); } @Test public void testExistingIntegerAtEnd() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 9); assertEquals(4, index); } @Test public void testNonExistingInteger() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 7); assertEquals(-1, index); } @Test public void testTooSmallInteger() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 0); assertEquals(-1, index); } @Test public void testTooLargeInteger() { Integer[] elements = new Integer[] { 1, 3, 4, 5, 9 }; int index = BinaryObjectSearch.binSearch(elements, 11); assertEquals(-1, index); } @Test public void testEqualInteger() { Integer[] elements = new Integer[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; int index = BinaryObjectSearch.binSearch(elements, 6); assertEquals(-1, index); } @Test public void testExistingStringFirstHalf() { String[] elements = new String[] { "A", "C", "F", "G", "K", "O", "T", "Z" }; int index = BinaryObjectSearch.binSearch(elements, "C"); assertEquals(1, index); } @Test public void testExistingStringSecondtHalf() { String[] elements = new String[] { "A", "C", "F", "G", "K", "O", "T", "Z" }; int index = BinaryObjectSearch.binSearch(elements, "O"); assertEquals(5, index); }
### Question: Matrix { public boolean equals(Matrix matrix) { return height == matrix.height && width == matrix.width && Arrays.equals(data, matrix.data); } Matrix(int height, int width, double[] data); Matrix(int height, int width); Matrix(int height, int width, double value); boolean equals(Matrix matrix); Matrix multiplyWithTime(Matrix matrix); Matrix multiply(Matrix matrix); Matrix multiplyNativeWithTime(Matrix matrix); Matrix multiplyNative(Matrix matrix); Matrix powerWithTime(int k); Matrix power(int k); Matrix powerNativeWithTime(int k); Matrix powerNative(int k); }### Answer: @Test public void testEquals() { Matrix matrix1 = new Matrix(2, 2, new double[]{1, 2, 3, 4}); Matrix matrix2 = new Matrix(2, 2, new double[]{1, 2, 3, 4}); Matrix matrix3 = new Matrix(2, 3, new double[]{1, 2, 3, 4, 5, 6}); Matrix matrix4 = new Matrix(0, 0, new double[]{}); Assert.assertTrue(matrix1.equals(matrix1)); Assert.assertTrue(matrix1.equals(matrix2)); Assert.assertFalse(matrix1.equals(matrix3)); Assert.assertFalse(matrix1.equals(matrix4)); }
### Question: Matrix { public Matrix multiply(Matrix matrix) { if (width != matrix.height) { throw new IllegalArgumentException("Invalid sizes"); } int index1 = 0, index3 = 0; Matrix newmatrix = new Matrix(height, matrix.width, null); for (int i = 0; i < height; i++) { for (int j = 0; j < matrix.width; j++) { double counter = 0.0; int index2 = 0; for (int k = 0; k < width; k++) { counter += data[index1 + k] * matrix.data[index2 + j]; index2 += matrix.width; } newmatrix.data[index3 + j] = counter; } index1 += width; index3 += matrix.width; } return newmatrix; } Matrix(int height, int width, double[] data); Matrix(int height, int width); Matrix(int height, int width, double value); boolean equals(Matrix matrix); Matrix multiplyWithTime(Matrix matrix); Matrix multiply(Matrix matrix); Matrix multiplyNativeWithTime(Matrix matrix); Matrix multiplyNative(Matrix matrix); Matrix powerWithTime(int k); Matrix power(int k); Matrix powerNativeWithTime(int k); Matrix powerNative(int k); }### Answer: @Test public void testMultiply() { Matrix matrix1 = new Matrix(2, 3, new double[]{1, 2, 3, 4, 5, 6}); Matrix matrix2 = new Matrix(3, 2, new double[]{3, 6, 2, 5, 1, 4}); Matrix matrix3 = new Matrix(2, 2, new double[]{10, 28, 28, 73}); Matrix matrix4 = matrix1.multiply(matrix2); Assert.assertTrue(matrix3.equals(matrix4)); Matrix matrix5 = matrix1.multiplyNative(matrix2); Assert.assertTrue(matrix3.equals(matrix5)); }
### Question: Matrix { public Matrix power(int k) { if (height != width) { throw new IllegalArgumentException("Matrix is not a square"); } if (k < 1) { throw new IllegalArgumentException("Invalid power"); } if (k == 1) { return this; } Matrix matrix = this; for (int i = 1; i < k; i++) { matrix = multiply(matrix); } return matrix; } Matrix(int height, int width, double[] data); Matrix(int height, int width); Matrix(int height, int width, double value); boolean equals(Matrix matrix); Matrix multiplyWithTime(Matrix matrix); Matrix multiply(Matrix matrix); Matrix multiplyNativeWithTime(Matrix matrix); Matrix multiplyNative(Matrix matrix); Matrix powerWithTime(int k); Matrix power(int k); Matrix powerNativeWithTime(int k); Matrix powerNative(int k); }### Answer: @Test public void testPower() { Matrix matrix1 = new Matrix(2, 2, new double[]{1, 2, 3, 4}); Matrix matrix2 = matrix1.powerNative(1); Assert.assertTrue(matrix1.equals(matrix2)); Matrix matrix3 = new Matrix(2, 2, new double[]{7, 10, 15, 22}); Matrix matrix4 = matrix1.power(2); Assert.assertTrue(matrix3.equals(matrix4)); Matrix matrix5 = new Matrix(2, 2, new double[]{37, 54, 81, 118}); Matrix matrix6 = matrix1.power(3); Assert.assertTrue(matrix5.equals(matrix6)); Matrix matrix7 = matrix1.powerNative(1); Assert.assertTrue(matrix1.equals(matrix7)); Matrix matrix8 = new Matrix(2, 2, new double[]{7, 10, 15, 22}); Matrix matrix9 = matrix1.powerNative(2); Assert.assertTrue(matrix8.equals(matrix9)); Matrix matrix10 = new Matrix(2, 2, new double[]{37, 54, 81, 118}); Matrix matrix11 = matrix1.powerNative(3); Assert.assertTrue(matrix10.equals(matrix11)); }
### Question: DataSet { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((movieList == null) ? 0 : movieList.hashCode()); result = prime * result + ((rentalList == null) ? 0 : rentalList.hashCode()); result = prime * result + ((userList == null) ? 0 : userList.hashCode()); return result; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testHashCode() throws Exception { DataSet ds2 = new DataSet(MovieRentalView.getDateFormatter()); assertEquals(ds.hashCode(), ds2.hashCode()); List<Movie> ml = ds2.getMovieList(); ml.clear(); ml.add(new Movie("Bla", RegularPriceCategory.getInstance())); assertTrue(ds.hashCode() != ds2.hashCode()); }
### Question: DataSet { public DataSet(DateFormat dateFormat) throws Exception { this.dateFormat = dateFormat; db = new Database(); db.initDatabase(); initLists(); } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testDataSet() throws Exception { assertNotNull(ds); }
### Question: DataSet { public List<IUser> getUserList() { return this.userList; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetterGetterUserList() { assertNotNull(ds.getUserList()); }
### Question: DataSet { public Object[][] getUserListAsObject() { int listSize = userList != null ? userList.size() : 0; Object[][] userArray = new Object[listSize][3]; if (userList != null) { int i = 0; for (IUser u : userList) { userArray[i][0] = u.getId(); userArray[i][1] = u.getName(); userArray[i][2] = u.getFirstName(); i++; } } return userArray; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetUserListAsObject() { Object[][] arr = ds.getUserListAsObject(); assertNotNull(arr); assertEquals(arr.length, ds.getUserList().size()); assertEquals(3, arr[0].length); }
### Question: DataSet { public IUser getUserByName(String name) { for (IUser c : userList) { if (c.getName().equalsIgnoreCase(name)) { return c; } } return null; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetUserByName() { User userNotFound = (User) ds.getUserByName("doesNotExist"); assertNull(userNotFound); User user = (User) ds.getUserByName("Meier"); assertNotNull(user); assertTrue(user.hasRentals()); }
### Question: DataSet { public IUser getUserById(int id) { for (IUser c : userList) { if (c.getId() == id) { return c; } } return null; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testRentalsOfUser() { User user = (User) ds.getUserById(1); assertNotNull(user); assertTrue(user.hasRentals()); }
### Question: DataSet { public List<Movie> getMovieList() { return this.movieList; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetterGetterMovieList() { assertNotNull(ds.getMovieList()); }
### Question: DataSet { public Object[][] getMovieListAsObject(boolean rented, boolean available) { ArrayList<Movie> movieArray = null; if (movieList != null) { movieArray = prepareMovieArray(rented, available); } Object[][] movieObjArray = new Object[movieArray.size()][5]; int i = 0; for (Movie m : movieArray) { movieObjArray[i++] = fillInMovieArrayElement(m); } return movieObjArray; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetMovieListAsObjectBooleanBoolean() { Object[][] arr = ds.getMovieListAsObject(false, false); assertNotNull(arr); arr = ds.getMovieListAsObject(false, true); assertNotNull(arr); arr = ds.getMovieListAsObject(true, false); assertNotNull(arr); arr = ds.getMovieListAsObject(true, true); assertNotNull(arr); } @Test public void testGetMovieListAsObject() { Object[][] arr = ds.getMovieListAsObject(); assertNotNull(arr); }
### Question: DataSet { public Movie getMovieById(long id) { for (int i = 0; i < movieList.size(); i++) { if (movieList.get(i).getId() == id) { return movieList.get(i); } } return null; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetMovieById() { Movie m = ds.getMovieById(1); assertNotNull(m); assertEquals(1, m.getId()); m = ds.getMovieById(-1000); assertNull(m); }
### Question: DataSet { public void updateMovie(Movie movie) { for (int i = 0; i < movieList.size(); i++) { if (movieList.get(i).getId() == movie.getId()) { movieList.get(i).setRented(movie.isRented()); movieList.get(i).setPriceCategory(movie.getPriceCategory()); } } } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testUpdateMovie() { Movie m1 = ds.getMovieById(1); m1.setRented(!m1.isRented()); ds.updateMovie(m1); Movie m2 = ds.getMovieById(1); assertEquals(m1, m2); }
### Question: DataSet { public List<Rental> getRentalList() { return this.rentalList; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetterGetterRentalList() { assertNotNull(ds.getRentalList()); }
### Question: DataSet { public Object[][] getRentalListAsObject() { int listSize = rentalList != null ? rentalList.size() : 0; Object[][] rentalArray = new Object[listSize][8]; if (rentalList != null) { int i = 0; for (Rental r : rentalList) { rentalArray[i][0] = r.getId(); rentalArray[i][1] = r.getRentalDays(); rentalArray[i][2] = dateFormat.format(r.getRentalDate()); rentalArray[i][3] = r.getUser().getName(); rentalArray[i][4] = r.getUser().getFirstName(); rentalArray[i][5] = r.getMovie().getTitle(); rentalArray[i][6] = r.calcRemainingDaysOfRental(new Date(Calendar.getInstance().getTimeInMillis())); rentalArray[i][7] = r.getRentalFee(); r.setRentalDays((Integer) rentalArray[i][1]); i++; } } return rentalArray; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetRentalListAsObject() { Object[][] arr = ds.getRentalListAsObject(); assertNotNull(arr); assertEquals(arr.length, ds.getRentalList().size()); assertEquals(8, arr[0].length); }
### Question: SQLUserDAO implements UserDAO { @Override public void delete(IUser user) { try { PreparedStatement ps = connection.prepareStatement(DELETE_SQL); ps.setInt(1, user.getId()); ps.execute(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testDelete() throws Exception { Statement s = connection.createStatement(); ResultSet r = s.executeQuery(COUNT_SQL); r.next(); int rows = r.getInt(1); assertEquals(3, rows); UserDAO dao = new SQLUserDAO(connection); User user = new User("Denzler", "Christoph"); user.setId(42); dao.delete(user); IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("CLIENTS"); InputStream stream = this.getClass().getResourceAsStream("UserDaoTestResult.xml"); IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(stream); ITable expectedTable = expectedDataSet.getTable("CLIENTS"); assertEquals(expectedTable, actualTable); connection.close(); dao.delete(user); }
### Question: SQLUserDAO implements UserDAO { @Override public List<IUser> getAll() { try { List<IUser> result = new LinkedList<IUser>(); PreparedStatement ps = connection.prepareStatement(GET_ALL_SQL); ResultSet r = ps.executeQuery(); while (r.next()) { result.add(readUser(r)); } r.close(); ps.close(); return result; } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testGetAll() throws DatabaseUnitException, SQLException, Exception { UserDAO dao = new SQLUserDAO(connection); List<IUser> userlist = dao.getAll(); ITable actualTable = (ITable) userlist; InputStream stream = this.getClass().getResourceAsStream("UserDaoTestData.xml"); IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(stream); ITable expectedTable = expectedDataSet.getTable("CLIENTS"); assertEquals(expectedTable, actualTable); stream = this.getClass().getResourceAsStream("UserDaoSingleRowTest.xml"); IDataSet dataSet = new FlatXmlDataSetBuilder().build(stream); DatabaseOperation.CLEAN_INSERT.execute(tester.getConnection(), dataSet); dao = new SQLUserDAO(tester.getConnection().getConnection()); userlist = dao.getAll(); assertEquals(1, userlist.size()); assertEquals("Bond", userlist.get(0).getName()); stream = this.getClass().getResourceAsStream("UserDaoEmpty.xml"); dataSet = new XmlDataSet(stream); DatabaseOperation.CLEAN_INSERT.execute(tester.getConnection(), dataSet); Connection conn = tester.getConnection().getConnection(); dao = new SQLUserDAO(conn); userlist = dao.getAll(); assertNotNull(userlist); assertEquals(0, userlist.size()); conn.close(); dao.getAll(); }
### Question: SQLUserDAO implements UserDAO { @Override public IUser getById(int id) { try { User result = null; PreparedStatement ps = connection.prepareStatement(GET_BY_ID_SQL); ps.setInt(1, id); ResultSet r = ps.executeQuery(); if (r.next()) { result = readUser(r); } r.close(); ps.close(); return result; } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testGetById() throws SQLException { UserDAO dao = new SQLUserDAO(connection); IUser user = dao.getById(42); assertEquals("Micky", user.getFirstName()); assertEquals("Mouse", user.getName()); assertEquals(42, user.getId()); connection.close(); dao.getById(42); }
### Question: SQLUserDAO implements UserDAO { @Override public List<IUser> getByName(String name) { try { List<IUser> result = new LinkedList<IUser>(); PreparedStatement ps = connection.prepareStatement(GET_BY_NAME_SQL); ps.setString(1, name); ResultSet r = ps.executeQuery(); while (r.next()) { result.add(readUser(r)); } r.close(); ps.close(); return result; } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testGetByName() throws SQLException { UserDAO dao = new SQLUserDAO(connection); List<IUser> userlist = dao.getByName("Duck"); assertEquals(2, userlist.size()); connection.close(); dao.getByName("Duck"); }
### Question: SQLUserDAO implements UserDAO { @Override public void saveOrUpdate(IUser user) { try { PreparedStatement ps = connection.prepareStatement(GET_BY_ID_SQL); ps.setInt(1, user.getId()); ResultSet r = ps.executeQuery(); if (r.next()) { PreparedStatement update = connection.prepareStatement(UPDATE_SQL); update.setString(1, user.getFirstName()); update.setString(2, user.getName()); update.setInt(3, user.getId()); update.execute(); connection.commit(); update.close(); } else { PreparedStatement insert = connection.prepareStatement(INSERT_SQL); insert.setInt(1, user.getId()); insert.setString(2, user.getFirstName()); insert.setString(3, user.getName()); insert.execute(); connection.commit(); insert.close(); } r.close(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testSaveOrUpdate() throws SQLException { Statement s = connection.createStatement(); ResultSet r = s.executeQuery(COUNT_SQL); r.next(); int rows0 = r.getInt(1); UserDAO dao = new SQLUserDAO(connection); IUser daisy = dao.getById(13); daisy.setFirstName("Daisy"); dao.saveOrUpdate(daisy); IUser actual = dao.getById(13); assertEquals(daisy.getFirstName(), actual.getFirstName()); r = s.executeQuery(COUNT_SQL); r.next(); int rows1 = r.getInt(1); assertEquals(rows0, rows1); User goofy = new User("Goofy", "Goofy"); goofy.setId(8); dao.saveOrUpdate(goofy); actual = dao.getById(8); assertEquals(goofy.getFirstName(), actual.getFirstName()); r = s.executeQuery(COUNT_SQL); r.next(); int rows2 = r.getInt(1); assertEquals(rows1 + 1, rows2); connection.close(); dao.saveOrUpdate(goofy); }
### Question: Database { public void initDatabase() throws Exception { connection = DatabaseJdbcDriver.loadDriver(); createDatabaseModel(); importData(); } void initDatabase(); List<IUser> initUserList(); List<Movie> initMovieList(); List<Rental> initRentalList(); }### Answer: @Test public void testInitDatabase() { try { database.initDatabase(); } catch (Exception e) { fail(e.getMessage()); } }
### Question: Rental { public Rental(IUser aUser, Movie aMovie, int nofRentalDays) { this(aUser, aMovie, nofRentalDays, new Date(Calendar.getInstance().getTimeInMillis())); if (aMovie.isRented()) { throw new IllegalStateException("movie is already rented!"); } aMovie.setRented(true); } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testRental() throws InterruptedException { Date before = new Date(Calendar.getInstance().getTimeInMillis()); Thread.sleep(10); Rental r = new Rental(u1, m1, 42); assertNotNull(r); assertTrue(u1.getRentals().contains(r)); assertTrue(m1.isRented()); assertEquals(42, r.getRentalDays()); Thread.sleep(10); Date after = new Date(Calendar.getInstance().getTimeInMillis()); assertTrue(before.before(r.getRentalDate())); assertTrue(after.after(r.getRentalDate())); assertEquals(u1, r.getUser()); assertEquals(m1, r.getMovie()); }
### Question: Rental { public int calcRemainingDaysOfRental(Date date) { if (date == null) { throw new NullPointerException("given date is not set!"); } Long diff = ((rentalDate.getTime() - date.getTime()) / 86400000) + rentalDays; setRentalDays(Math.abs(diff.intValue())); return diff.intValue(); } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testCalcRemainingDaysOfRental() { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2008, 10, 05); Date today = new Date(cal.getTimeInMillis()); cal.clear(); cal.set(2008, 10, 06); Date tomorrow = new Date(cal.getTimeInMillis()); Rental r = new Rental(u1, m1, 1); r.setRentalDate(today); int remaining = r.calcRemainingDaysOfRental(tomorrow); assertEquals(0, remaining); try { r.calcRemainingDaysOfRental(null); fail(); } catch (NullPointerException npe) { assertEquals("given date is not set!", npe.getMessage()); } }
### Question: Rental { @Override public boolean equals(Object o) { boolean result = this == o; if (!result) { if (o instanceof Rental) { Rental other = (Rental) o; result = initialized ? id == other.id : initialized == other.initialized; result &= this.movie.equals(other.movie); result &= this.user.equals(other.user); } } return result; } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test @Ignore public void testEquals() { }
### Question: Rental { @Override public int hashCode() { int result = initialized ? id : 0; result = result * 19 + movie.hashCode(); result = result * 19 + user.hashCode(); return result; } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testHashCode() { Rental x = new Rental(u1, m1, 5); m1.setRented(false); Rental y = new Rental(u1, m1, 5); assertEquals(x.hashCode(), y.hashCode()); x.setId(42); assertTrue(x.hashCode() != y.hashCode()); y.setId(42); assertEquals(x.hashCode(), y.hashCode()); x.setMovie(m2); assertTrue(x.hashCode() != y.hashCode()); y.setMovie(m2); assertEquals(x.hashCode(), y.hashCode()); x.setUser(u2); assertTrue(x.hashCode() != y.hashCode()); y.setUser(u2); assertEquals(x.hashCode(), y.hashCode()); }
### Question: NewReleasePriceCategory extends PriceCategory { @Override public double getCharge(int daysRented) { if (daysRented > 0) { return daysRented * 3; } return 0.0d; } private NewReleasePriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override int getFrequentRenterPoints(int daysRented); @Override String toString(); static NewReleasePriceCategory getInstance(); }### Answer: @Test public void testGetCharge() { assertEquals(0.0d, nrpc.getCharge(-5), tolerance); assertEquals(0.0d, nrpc.getCharge(0), tolerance); assertEquals(3.0d, nrpc.getCharge(1), tolerance); assertEquals(6.0d, nrpc.getCharge(2), tolerance); assertEquals(66.0d, nrpc.getCharge(22), tolerance); }
### Question: NewReleasePriceCategory extends PriceCategory { @Override public int getFrequentRenterPoints(int daysRented) { int result = 0; if (daysRented > 0) { if (daysRented == 1) { result = 1; } else { result = 2; } } return result; } private NewReleasePriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override int getFrequentRenterPoints(int daysRented); @Override String toString(); static NewReleasePriceCategory getInstance(); }### Answer: @Test public void testGetFrequentRenterPoints() { assertEquals(0, nrpc.getFrequentRenterPoints(-3)); assertEquals(0, nrpc.getFrequentRenterPoints(0)); assertEquals(1, nrpc.getFrequentRenterPoints(1)); assertEquals(2, nrpc.getFrequentRenterPoints(2)); assertEquals(2, nrpc.getFrequentRenterPoints(50)); }
### Question: NewReleasePriceCategory extends PriceCategory { @Override public String toString() { return "New Release"; } private NewReleasePriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override int getFrequentRenterPoints(int daysRented); @Override String toString(); static NewReleasePriceCategory getInstance(); }### Answer: @Test public void testToString() { assertEquals("New Release", nrpc.toString()); }
### Question: Stock { public int addToStock(Movie movie) { Integer i = stock.get(movie.getTitle()); int inStock = (i == null) ? 0 : i; stock.put(movie.getTitle(), ++inStock); return inStock; } int addToStock(Movie movie); int removeFromStock(Movie movie); int getInStock(String title); void removeFromStock(String title); void addLowStockListener(LowStockListener l); void removeLowStockListener(LowStockListener l); }### Answer: @Test public void testAddToStock() { testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); assertEquals(2, testStock.getInStock(mockMovie.getTitle())); }
### Question: Stock { public int removeFromStock(Movie movie) { String title = movie.getTitle(); Integer i = stock.get(title); int inStock = (i == null) ? 0 : i; if (inStock <= 0) { throw new MovieRentalException("no video in stock"); } stock.put(title, --inStock); notifyListeners(movie, inStock); return inStock; } int addToStock(Movie movie); int removeFromStock(Movie movie); int getInStock(String title); void removeFromStock(String title); void addLowStockListener(LowStockListener l); void removeLowStockListener(LowStockListener l); }### Answer: @Test(expected=MovieRentalException.class) public void testRemoveFromStock() throws Exception { testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 3); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 2); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 1); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 0); testStock.removeFromStock(mockMovie.getTitle()); }
### Question: User implements IUser { public User(String aName, String aFirstName) { if (aName != null) { if ((aName.length() == 0) || (aName.length() > 40)) { throw new MovieRentalException("invalid name value"); } } else { throw new NullPointerException("invalid name value"); } checkIfFirstNameValid(aFirstName); this.name = aName; this.firstName = aFirstName; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test public void testUser() { User u = new User(NAME, FIRSTNAME); assertNotNull("u should not be null", u); String n = u.getName(); String f = u.getFirstName(); assertEquals(NAME, n); assertEquals(FIRSTNAME, f); List<Rental> rentals = u.getRentals(); assertNotNull("rentals list should be empty, not null", rentals); assertEquals(0, rentals.size()); }
### Question: User implements IUser { public double getCharge() { double result = 0.0d; for (Rental rental : rentals) { result += rental.getMovie().getPriceCategory().getCharge(rental.getRentalDays()); } return result; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test public void testGetCharge() { double delta=1e-6; User u = new User(NAME, FIRSTNAME); double charge = u.getCharge(); assertEquals(0.0d, charge, delta); PriceCategory regular = RegularPriceCategory.getInstance(); Movie mov = new Movie("A", regular); Rental r = new Rental(u, mov, 1); charge = r.getRentalFee(); assertEquals(charge, u.getCharge(), delta); mov = new Movie("B", regular); r = new Rental(u, mov, 1); charge += r.getRentalFee(); mov = new Movie("C", regular); r = new Rental(u, mov, 1); charge += r.getRentalFee(); assertEquals(charge, u.getCharge(), delta); }
### Question: User implements IUser { @Override public boolean equals(Object o) { boolean result = this == o; if (!result) { if (o instanceof User) { User other = (User) o; result = initialized ? id == other.id : initialized == other.initialized; result &= name.equals(other.name); result &= firstName.equals(other.firstName); } } return result; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test @Ignore public void testEquals() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { }
### Question: User implements IUser { @Override public int hashCode() { int result = (initialized) ? id : 0; result = 19 * result + name.hashCode(); result = 19 * result + firstName.hashCode(); return result; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test public void testHashCode() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { IUser x = new User(NAME, FIRSTNAME); IUser y = new User(NAME, FIRSTNAME); assertEquals(x.hashCode(), y.hashCode()); x.setId(42); assertTrue(x.hashCode() != y.hashCode()); y.setId(42); assertEquals(x.hashCode(), y.hashCode()); }