method2testcases stringlengths 118 3.08k |
|---|
### Question:
SwicoBillInformation { public void setInvoiceNumber(String invoiceNumber) { this.invoiceNumber = invoiceNumber; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setInvoiceNumber() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setInvoiceNumber("ABC"); assertEquals("ABC", billInformation.getInvoiceNumber()); } |
### Question:
AlternativeScheme implements Serializable { @Override public String toString() { return "AlternativeScheme{" + "name='" + name + '\'' + ", instruction='" + instruction + '\'' + '}'; } AlternativeScheme(); AlternativeScheme(String name, String instruction); String getName(); void setName(String name); String getInstruction(); void setInstruction(String instruction); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void toStringTest() { AlternativeScheme scheme = new AlternativeScheme("Paymit", "PM,12341234,1241234"); String text = scheme.toString(); assertEquals("AlternativeScheme{name='Paymit', instruction='PM,12341234,1241234'}", text); } |
### Question:
SwicoBillInformation { public void setInvoiceDate(LocalDate invoiceDate) { this.invoiceDate = invoiceDate; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setInvoiceDate() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setInvoiceDate(LocalDate.of(2020, 6, 30)); assertEquals(LocalDate.of(2020, 6, 30), billInformation.getInvoiceDate()); } |
### Question:
SwicoBillInformation { public void setCustomerReference(String customerReference) { this.customerReference = customerReference; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setCustomerReference() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setCustomerReference("1234-ABC"); assertEquals("1234-ABC", billInformation.getCustomerReference()); } |
### Question:
SwicoBillInformation { public void setVatNumber(String vatNumber) { this.vatNumber = vatNumber; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setVatNumber() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatNumber("109030864"); assertEquals("109030864", billInformation.getVatNumber()); } |
### Question:
SwicoBillInformation { public void setVatDate(LocalDate vatDate) { this.vatDate = vatDate; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setVatDate() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatDate(LocalDate.of(2020, 3, 1)); assertEquals(LocalDate.of(2020, 3, 1), billInformation.getVatDate()); } |
### Question:
SwicoBillInformation { public void setVatStartDate(LocalDate vatStartDate) { this.vatStartDate = vatStartDate; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setVatStartDate() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatStartDate(LocalDate.of(2019, 3, 1)); assertEquals(LocalDate.of(2019, 3, 1), billInformation.getVatStartDate()); } |
### Question:
SwicoBillInformation { public void setVatEndDate(LocalDate vatEndDate) { this.vatEndDate = vatEndDate; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setVatEndDate() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatEndDate(LocalDate.of(2020, 2, 29)); assertEquals(LocalDate.of(2020, 2, 29), billInformation.getVatEndDate()); } |
### Question:
SwicoBillInformation { public void setVatRate(BigDecimal vatRate) { this.vatRate = vatRate; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setVatRate() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatRate(BigDecimal.valueOf(7.7)); assertEquals(7.7, billInformation.getVatRate().doubleValue()); } |
### Question:
SwicoBillInformation { public void setVatRateDetails(List<RateDetail> vatRateDetails) { this.vatRateDetails = vatRateDetails; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setVatRateDetails() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatRateDetails(Arrays.asList( new RateDetail(BigDecimal.valueOf(8, 0), BigDecimal.valueOf(1000, 0)), new RateDetail(BigDecimal.valueOf(25, 1), BigDecimal.valueOf(400, 0)) )); assertEquals(2, billInformation.getVatRateDetails().size()); assertEquals(8.0, billInformation.getVatRateDetails().get(0).getRate().doubleValue()); assertEquals(400.0, billInformation.getVatRateDetails().get(1).getAmount().doubleValue()); } |
### Question:
SwicoBillInformation { public void setVatImportTaxes(List<RateDetail> vatImportTaxes) { this.vatImportTaxes = vatImportTaxes; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setVatImportTaxes() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatImportTaxes(Arrays.asList( new RateDetail(BigDecimal.valueOf(77, 1), BigDecimal.valueOf(4812, 2)), new RateDetail(BigDecimal.valueOf(25, 1), BigDecimal.valueOf(1723, 2)) )); assertEquals(2, billInformation.getVatImportTaxes().size()); assertEquals(7.7, billInformation.getVatImportTaxes().get(0).getRate().doubleValue()); assertEquals(17.23, billInformation.getVatImportTaxes().get(1).getAmount().doubleValue()); } |
### Question:
SwicoBillInformation { public void setPaymentConditions(List<PaymentCondition> paymentConditions) { this.paymentConditions = paymentConditions; } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void setPaymentConditions() { SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setPaymentConditions(Arrays.asList( new PaymentCondition(BigDecimal.valueOf(2.0), 10), new PaymentCondition(BigDecimal.ZERO, 30) )); assertEquals(2, billInformation.getPaymentConditions().size()); assertEquals(2.0, billInformation.getPaymentConditions().get(0).getDiscount().doubleValue()); assertEquals(30, billInformation.getPaymentConditions().get(1).getDays()); } |
### Question:
AlternativeScheme implements Serializable { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlternativeScheme that = (AlternativeScheme) o; return Objects.equals(name, that.name) && Objects.equals(instruction, that.instruction); } AlternativeScheme(); AlternativeScheme(String name, String instruction); String getName(); void setName(String name); String getInstruction(); void setInstruction(String instruction); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void testEquals() { AlternativeScheme scheme1 = new AlternativeScheme("Paymit", "PM,12341234,1241234"); AlternativeScheme scheme2 = new AlternativeScheme("Paymit", "PM,12341234,1241234"); assertEquals(scheme1, scheme2); assertEquals(scheme1, scheme2); scheme2.setName("TWINT"); assertNotEquals(scheme1, scheme2); } |
### Question:
SwicoBillInformation { @Override public int hashCode() { return Objects.hash(invoiceNumber, invoiceDate, customerReference, vatNumber, vatDate, vatStartDate, vatEndDate, vatRate, vatRateDetails, vatImportTaxes, paymentConditions); } String getInvoiceNumber(); void setInvoiceNumber(String invoiceNumber); LocalDate getInvoiceDate(); void setInvoiceDate(LocalDate invoiceDate); String getCustomerReference(); void setCustomerReference(String customerReference); String getVatNumber(); void setVatNumber(String vatNumber); LocalDate getVatDate(); void setVatDate(LocalDate vatDate); LocalDate getVatStartDate(); void setVatStartDate(LocalDate vatStartDate); LocalDate getVatEndDate(); void setVatEndDate(LocalDate vatEndDate); BigDecimal getVatRate(); void setVatRate(BigDecimal vatRate); List<RateDetail> getVatRateDetails(); void setVatRateDetails(List<RateDetail> vatRateDetails); List<RateDetail> getVatImportTaxes(); void setVatImportTaxes(List<RateDetail> vatImportTaxes); List<PaymentCondition> getPaymentConditions(); void setPaymentConditions(List<PaymentCondition> paymentConditions); LocalDate getDueDate(); String encodeAsText(); static SwicoBillInformation decodeText(String text); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void testHashCode() { SwicoBillInformation info1 = createBillInformation(); SwicoBillInformation info2 = createBillInformation(); assertEquals(info1.hashCode(), info2.hashCode()); } |
### Question:
ValidationResult implements Serializable { public void setCleanedBill(Bill cleanedBill) { this.cleanedBill = cleanedBill; } List<ValidationMessage> getValidationMessages(); boolean hasMessages(); boolean hasWarnings(); boolean hasErrors(); boolean isValid(); void addMessage(Type type, String field, String messageKey); void addMessage(Type type, String field, String messageKey, String[] messageParameters); Bill getCleanedBill(); void setCleanedBill(Bill cleanedBill); String getDescription(); }### Answer:
@Test void setCleanedBill() { ValidationResult result = new ValidationResult(); result.setCleanedBill(SampleData.getExample2()); assertEquals(SampleData.getExample2(), result.getCleanedBill()); } |
### Question:
AlternativeScheme implements Serializable { @Override public int hashCode() { return Objects.hash(name, instruction); } AlternativeScheme(); AlternativeScheme(String name, String instruction); String getName(); void setName(String name); String getInstruction(); void setInstruction(String instruction); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void testHashCode() { AlternativeScheme scheme = new AlternativeScheme("Paymit", "PM,12341234,1241234"); assertEquals(1266162573, scheme.hashCode()); } |
### Question:
SphinxNode extends AbstractInputNode { @Override public List<LanguageName> getAvailableLanguages() { return getSettings() != null ? getSettings().getLanguages() : Plugin.getAvailableLanguages(); } @Override AudioFormat getAudioFormat(); @Override RecognitionExecutor createRecognitionExecutor(com.clt.srgf.Grammar recGrammar); @Override Device getDevice(); @Override List<LanguageName> getAvailableLanguages(); @Override LanguageName getDefaultLanguage(); }### Answer:
@Test(timeout = 10000) public void testAvailableLanguages() { SphinxNode node = createNode(); List<LanguageName> langs = node.getAvailableLanguages(); assertNotNull(langs); assertFalse(langs.isEmpty()); } |
### Question:
Sphinx extends SphinxBaseRecognizer { @Override protected RecognitionResult startImpl() throws SpeechException { fireRecognizerEvent(RecognizerEvent.RECOGNIZER_LOADING); assert context != null : "cannot start recognition without a context"; csr = context.getRecognizer(); context.getVadListener().setRecognizer(this); vadInSpeech = false; SpeechResult speechResult; boolean isMatch; stopping = false; csr.startRecognition(); do { fireRecognizerEvent(RecognizerEvent.RECOGNIZER_READY); speechResult = csr.getResult(); if (speechResult == null) break; isMatch = isMatch(speechResult); if (!isMatch) fireRecognizerEvent(new RecognizerEvent(this, RecognizerEvent.INVALID_RESULT, sphinx2DOSResult(speechResult))); } while (!isMatch && !stopping && isActive()); csr.stopRecognition(); if (speechResult != null && !stopping) { RecognitionResult sphinxResult = sphinx2DOSResult(speechResult); fireRecognizerEvent(sphinxResult); return sphinxResult; } else { return null; } } Sphinx(); SphinxLanguageSettings getLanguageSettings(Language l); @Override Language[] getLanguages(); @Override void setContext(RecognitionContext context); @Override RecognitionContext getContext(); @Override SphinxContext createTemporaryContext(Grammar g, Domain domain); }### Answer:
@Test(expected = NullPointerException.class, timeout=10000) public void invalidRecognitionSetupTest() throws SpeechException { Sphinx sphinx = new Sphinx(); try { sphinx.startImpl(); } catch (AssertionError | NullPointerException e) { throw new NullPointerException(); } } |
### Question:
DistStageAck implements Serializable { public void setRemoteException(Throwable remoteException) { StringBuilder sb = new StringBuilder(); Set<Throwable> causes = new HashSet(); while (remoteException != null) { sb.append(remoteException.toString()); StackTraceElement[] stackTraceElements = remoteException.getStackTrace(); if (stackTraceElements != null && stackTraceElements.length > 0) { for (StackTraceElement ste : stackTraceElements) { sb.append("\n\t at ").append(ste.toString()); } sb.append("\nsuppressed: "); sb.append(Arrays.toString(remoteException.getSuppressed())); if (remoteException.getCause() != null) { sb.append("\ncaused by: "); remoteException = remoteException.getCause(); if (!causes.add(remoteException)) { break; } } else { break; } } } remoteExceptionString = sb.append('\n').toString(); } DistStageAck(WorkerState workerState); T error(String message); T error(String message, Throwable exception); int getWorkerIndex(); boolean isError(); void setRemoteException(Throwable remoteException); @Override String toString(); void setDuration(long duration); long getDuration(); }### Answer:
@Test(timeOut = 500) public void testInfiniteLoopInExceptionCause() { Exception exception = new Exception(); Exception exception1 = new Exception(); exception1.initCause(exception); exception.initCause(exception1); DistStageAck distStageAck = new DistStageAck(new WorkerState()); distStageAck.setRemoteException(exception); } |
### Question:
XsltConverter implements Converter<String> { public boolean isXsltAttribute(String file) { boolean xslt = false; if (file != null && !file.trim().isEmpty()) { xslt = file.toLowerCase().startsWith(XSLT_PREFIX); } return xslt; } boolean isXsltAttribute(String file); @Override String convert(String file, Type type); @Override String convertToString(String file); @Override String allowedPattern(Type type); static File getFile(String filePath); }### Answer:
@Test public void testIsXsltAttribute() { Assert.assertTrue(new XsltConverter().isXsltAttribute("xslt(foo, bar)")); Assert.assertFalse(new XsltConverter().isXsltAttribute("xslt/foo.xml")); Assert.assertFalse(new XsltConverter().isXsltAttribute("foo/bar.xml")); Assert.assertFalse(new XsltConverter().isXsltAttribute(null)); } |
### Question:
LineChart extends ComparisonChart { @Override public void addValue(double value, double deviation, Comparable seriesName, double xValue, String xString) { YIntervalSeries series = seriesMap.get(seriesName); if (series == null) { seriesMap.put(seriesName, series = new YIntervalSeries(seriesName)); dataset.addSeries(series); } upperRange = Math.max(upperRange, Math.min(value + deviation, 3 * value)); series.add(xValue, value, value - deviation, value + deviation); if (xString != null) { iterationValues.put(xValue, xString); } } LineChart(String domainLabel, String rangeLabel); @Override void addValue(double value, double deviation, Comparable seriesName, double xValue, String xString); }### Answer:
@Test public void test() { LineChart chart = new LineChart("foos", "bars"); Random random = new Random(); for (int category = 0; category < 3; category++) { double lastValue = 0, lastDev = 1; for (int i = 0; i < 30; ++i) { lastValue = lastValue + (random.nextBoolean() ? 1 : -1); lastDev = lastDev + random.nextDouble() - 0.3; chart.addValue(lastValue, lastDev, "Serie" + category, i, String.valueOf(Math.pow(2, i))); } } try { chart.setHeight(500).setWidth(600).save("/tmp/foobar.png"); } catch (IOException e) { e.printStackTrace(); } } |
### Question:
DataUtils { public static String eval(String statement, JsonObject data) { for (String key : data.getMap().keySet()) { DataItem dataItem = new DataItem(data.getJsonObject(key)); statement = eval(statement, dataItem); } return statement; } static String eval(String statement, JsonObject data); static String eval(String statement, DataItem dataItem); static List<Integer> parseIntList(String value); }### Answer:
@Test public void evalTest() { DataItem dataItem = new DataItem() .setID("SHELVED_LIST") .setType(DataItem.Type.STRING) .setValue("100"); JsonObject data = new JsonObject().put(dataItem.getID(), dataItem.json()); String shelvedList = DataUtils.eval("${data.SHELVED_LIST}", data); Assert.assertEquals("Data evaluation for ${data.SHELVED_LIST} should be set to 100", "100", shelvedList); } |
### Question:
FileUtils { public static String extension(Path path) { String name = path.toFile().getName(); int dotIndex = name.lastIndexOf(DOT); if (dotIndex > 0) { return name.substring(dotIndex); } return EMPTY; } static Path find(File dir, String pattern); static Path tryFind(File dir, String pattern); static String slashify(String path); static String unslashify(String path); static boolean copy(File src, File dest); static void chmod757(String path); static boolean chmod(String path, boolean recursive,
boolean readable, boolean writable, boolean executable); static String baseName(String path); static String extension(Path path); static void createIfAbsent(FileSystem fs, String path, Handler<AsyncResult<Void>> handler); static void deleteIfPresent(FileSystem fs, String path, Handler<AsyncResult<Void>> handler); static void readFiles(FileSystem fs, String path, String filter,
Handler<AsyncResult<Map<String, String>>> handler); static List<String> readResource(String resourcePath); static final String NEW_LINE; static final String SLASH; static final String DOT_SLASH; static final String COLON; }### Answer:
@Test public void extensionTest() { Assert.assertEquals("Extension should be 'js'.", ".js", FileUtils.extension(new File("/buildpal/core/util/script.js").toPath())); } |
### Question:
AuthConfigUtils { public static byte[] hash(final char[] data, final byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC); PBEKeySpec spec = new PBEKeySpec(data, salt, ITERATIONS, KEY_LENGTH); SecretKey key = secretKeyFactory.generateSecret(spec); return key.getEncoded(); } static JsonObject getAuthConfig(JsonObject config); static JsonObject getVaultConfig(JsonObject config); static String getVaultKey(JsonObject config); static boolean isLdapEnabled(JsonObject config); static JsonObject getLdapConfig(JsonObject config); static String getLdapUrl(JsonObject config); static List<MessageFormat> getUserDnPatterns(JsonObject config); static String[] getDisplayNameAttributeID(JsonObject config); static byte[] hash(final char[] data, final byte[] salt); }### Answer:
@Test public void hashTest() throws Exception { Vault vault = new Vault(KEY, PATH); byte[] hash1 = AuthConfigUtils.hash("test".toCharArray(), SALT); byte[] hash2 = AuthConfigUtils.hash("test".toCharArray(), SALT); byte[] hash3 = AuthConfigUtils.hash("tEst".toCharArray(), SALT); Assert.assertTrue("Hashes of the same string should be equal.", Arrays.equals(hash1, hash2)); Assert.assertFalse("Hashes of the different strings should not be equal.", Arrays.equals(hash2, hash3)); } |
### Question:
DashOTransformer implements Transformer { public static String decrypt(String input) { if (isEmpty(input)) { return input; } char[] inputChars = input.toCharArray(); int length = inputChars.length; char[] inputCharsCopy = new char[length]; int j = 0; int i = 0; while (j < length) { inputCharsCopy[j] = ((char) (inputChars[j] - '\1' ^ i)); i = (char) (i + 1); j++; } return new String(inputCharsCopy); } DashOTransformer(String jarfile); static String decrypt(String input); void setDecryptor(); void removeStringEncryption(); void dumpJar(String path); void transform(); }### Answer:
@Test(dataProvider = "inputData") public void testDecrypt(String input, String outputExpected) throws Exception { final String outputActual = DashOTransformer.decrypt(input); assertEquals(outputActual, outputExpected); } |
### Question:
StanbolNamespacePrefixService implements NamespacePrefixService, NamespacePrefixProvider { @Override public String getNamespace(String prefix) { String namespace; mappingsLock.readLock().lock(); try { namespace = prefixMap.get(prefix); } finally { mappingsLock.readLock().unlock(); } if(namespace == null){ ServiceReference[] refs = getSortedProviderReferences(); for(int i=0;namespace == null && i<refs.length;i++){ NamespacePrefixProvider provider = getService(refs[i]); if(provider != null){ namespace = provider.getNamespace(prefix); } } } return namespace; } StanbolNamespacePrefixService(); StanbolNamespacePrefixService(File mappingFile); void importPrefixMappings(InputStream in); static NamespacePrefixService getInstance(); @Override String getNamespace(String prefix); @Override String getPrefix(String namespace); @Override List<String> getPrefixes(String namespace); @Override String setPrefix(String prefix, String namespace); @Override String getFullName(String shortNameOrUri); @Override String getShortName(String uri); }### Answer:
@Test public void testInitialisation(){ Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("urn:example.text:",service.getNamespace("urn_test")); } |
### Question:
URIUtils { public static IRI upOne(IRI iri) { return upOne(iri.toURI()); } private URIUtils(); static IRI createIRI(org.apache.clerezza.commons.rdf.IRI uri); static org.apache.clerezza.commons.rdf.IRI createIRI(IRI uri); static IRI desanitize(IRI iri); static String desanitize(String iri); static IRI sanitize(IRI iri); static String sanitize(String iri); static IRI upOne(IRI iri); static IRI upOne(URI uri); }### Answer:
@Test public void testUpOne() throws Exception { assertEquals(_BASE + ".owl", URIUtils.upOne(iri_hash).toString()); assertEquals(_BASE, URIUtils.upOne(iri_slash).toString()); assertEquals(_BASE, URIUtils.upOne(iri_slash_end).toString()); assertEquals(_BASE, URIUtils.upOne(iri_query).toString()); assertEquals(_BASE + "/", URIUtils.upOne(iri_slash_query).toString()); } |
### Question:
JenaToClerezzaConverter { public static com.hp.hpl.jena.graph.Graph clerezzaGraphToJenaGraph(org.apache.clerezza.commons.rdf.Graph mGraph){ Model jenaModel = clerezzaGraphToJenaModel(mGraph); if(jenaModel != null){ return jenaModel.getGraph(); } else{ return null; } } private JenaToClerezzaConverter(); static List<Triple> jenaModelToClerezzaTriples(Model model); static org.apache.clerezza.commons.rdf.Graph jenaModelToClerezzaGraph(Model model); static Model clerezzaGraphToJenaModel(org.apache.clerezza.commons.rdf.Graph mGraph); static com.hp.hpl.jena.graph.Graph clerezzaGraphToJenaGraph(org.apache.clerezza.commons.rdf.Graph mGraph); }### Answer:
@Test public void testGraphToJenaGraph(){ com.hp.hpl.jena.graph.Graph jGraph = JenaToClerezzaConverter.clerezzaGraphToJenaGraph(mGraph); ExtendedIterator<com.hp.hpl.jena.graph.Triple> tripleIt = jGraph.find(null, null, null); while(tripleIt.hasNext()){ com.hp.hpl.jena.graph.Triple triple = tripleIt.next(); log.info(triple.toString()); } } |
### Question:
JenaToClerezzaConverter { public static Model clerezzaGraphToJenaModel(org.apache.clerezza.commons.rdf.Graph mGraph){ ByteArrayOutputStream out = new ByteArrayOutputStream(); SerializingProvider serializingProvider = new JenaSerializerProvider(); serializingProvider.serialize(out, mGraph, SupportedFormat.RDF_XML); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); Model jenaModel = ModelFactory.createDefaultModel(); jenaModel.read(in, null); return jenaModel; } private JenaToClerezzaConverter(); static List<Triple> jenaModelToClerezzaTriples(Model model); static org.apache.clerezza.commons.rdf.Graph jenaModelToClerezzaGraph(Model model); static Model clerezzaGraphToJenaModel(org.apache.clerezza.commons.rdf.Graph mGraph); static com.hp.hpl.jena.graph.Graph clerezzaGraphToJenaGraph(org.apache.clerezza.commons.rdf.Graph mGraph); }### Answer:
@Test public void testGraphToJenaModel(){ Model model = JenaToClerezzaConverter.clerezzaGraphToJenaModel(mGraph); StmtIterator stmtIt = model.listStatements(); while(stmtIt.hasNext()){ Statement statement = stmtIt.next(); log.info(statement.toString()); } } |
### Question:
JenaToClerezzaConverter { public static org.apache.clerezza.commons.rdf.Graph jenaModelToClerezzaGraph(Model model){ ByteArrayOutputStream out = new ByteArrayOutputStream(); model.write(out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); ParsingProvider parser = new JenaParserProvider(); org.apache.clerezza.commons.rdf.Graph mGraph = new SimpleGraph(); parser.parse(mGraph,in, SupportedFormat.RDF_XML, null); return mGraph; } private JenaToClerezzaConverter(); static List<Triple> jenaModelToClerezzaTriples(Model model); static org.apache.clerezza.commons.rdf.Graph jenaModelToClerezzaGraph(Model model); static Model clerezzaGraphToJenaModel(org.apache.clerezza.commons.rdf.Graph mGraph); static com.hp.hpl.jena.graph.Graph clerezzaGraphToJenaGraph(org.apache.clerezza.commons.rdf.Graph mGraph); }### Answer:
@Test public void testModelToGraph(){ Graph mGraph = JenaToClerezzaConverter.jenaModelToClerezzaGraph(model); Iterator<Triple> tripleIt = mGraph.iterator(); while(tripleIt.hasNext()){ Triple triple = tripleIt.next(); log.info(triple.toString()); } } |
### Question:
JenaToClerezzaConverter { public static List<Triple> jenaModelToClerezzaTriples(Model model){ ArrayList<Triple> clerezzaTriples = new ArrayList<Triple>(); org.apache.clerezza.commons.rdf.Graph mGraph = jenaModelToClerezzaGraph(model); Iterator<Triple> tripleIterator = mGraph.iterator(); while(tripleIterator.hasNext()){ Triple triple = tripleIterator.next(); clerezzaTriples.add(triple); } return clerezzaTriples; } private JenaToClerezzaConverter(); static List<Triple> jenaModelToClerezzaTriples(Model model); static org.apache.clerezza.commons.rdf.Graph jenaModelToClerezzaGraph(Model model); static Model clerezzaGraphToJenaModel(org.apache.clerezza.commons.rdf.Graph mGraph); static com.hp.hpl.jena.graph.Graph clerezzaGraphToJenaGraph(org.apache.clerezza.commons.rdf.Graph mGraph); }### Answer:
@Test public void testModelToClerezzaTriples(){ Collection<Triple> triples = JenaToClerezzaConverter.jenaModelToClerezzaTriples(model); for(Triple triple : triples){ log.info(triple.toString()); } } |
### Question:
OWLAPIToClerezzaConverter { public static OWLOntology clerezzaGraphToOWLOntology(org.apache.clerezza.commons.rdf.Graph graph) { OWLOntologyManager mgr = OWLManager.createOWLOntologyManager(); mgr.addIRIMapper(new PhonyIRIMapper(Collections.<IRI> emptySet())); return clerezzaGraphToOWLOntology(graph, mgr); } private OWLAPIToClerezzaConverter(); static List<Triple> owlOntologyToClerezzaTriples(OWLOntology ontology); static org.apache.clerezza.commons.rdf.Graph owlOntologyToClerezzaGraph(OWLOntology ontology); static OWLOntology clerezzaGraphToOWLOntology(org.apache.clerezza.commons.rdf.Graph graph); static OWLOntology clerezzaGraphToOWLOntology(org.apache.clerezza.commons.rdf.Graph graph,
OWLOntologyManager ontologyManager); }### Answer:
@Test public void testGraphToOWLOntology() { OWLOntology ontology = OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(mGraph); int axiomCount = ontology.getAxiomCount(); log.info("The ontology contatins " + axiomCount + " axioms: "); Set<OWLAxiom> axioms = ontology.getAxioms(); for (OWLAxiom axiom : axioms) { log.info(" " + axiom.toString()); } } |
### Question:
OWLAPIToClerezzaConverter { public static org.apache.clerezza.commons.rdf.Graph owlOntologyToClerezzaGraph(OWLOntology ontology) { org.apache.clerezza.commons.rdf.Graph mGraph = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); OWLOntologyManager manager = ontology.getOWLOntologyManager(); try { manager.saveOntology(ontology, new RDFXMLOntologyFormat(), out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); ParsingProvider parser = new JenaParserProvider(); mGraph = new SimpleGraph(); parser.parse(mGraph, in, SupportedFormat.RDF_XML, null); } catch (OWLOntologyStorageException e) { log.error("Failed to serialize OWL Ontology " + ontology + "for conversion", e); } return mGraph; } private OWLAPIToClerezzaConverter(); static List<Triple> owlOntologyToClerezzaTriples(OWLOntology ontology); static org.apache.clerezza.commons.rdf.Graph owlOntologyToClerezzaGraph(OWLOntology ontology); static OWLOntology clerezzaGraphToOWLOntology(org.apache.clerezza.commons.rdf.Graph graph); static OWLOntology clerezzaGraphToOWLOntology(org.apache.clerezza.commons.rdf.Graph graph,
OWLOntologyManager ontologyManager); }### Answer:
@Test public void testOWLOntologyToGraph() { Graph mGraph = OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph(ontology); Iterator<Triple> tripleIt = mGraph.iterator(); while (tripleIt.hasNext()) { Triple triple = tripleIt.next(); log.info(triple.toString()); } } |
### Question:
OWLAPIToClerezzaConverter { public static List<Triple> owlOntologyToClerezzaTriples(OWLOntology ontology) { ArrayList<Triple> clerezzaTriples = new ArrayList<Triple>(); org.apache.clerezza.commons.rdf.Graph mGraph = owlOntologyToClerezzaGraph(ontology); Iterator<Triple> tripleIterator = mGraph.iterator(); while (tripleIterator.hasNext()) { Triple triple = tripleIterator.next(); clerezzaTriples.add(triple); } return clerezzaTriples; } private OWLAPIToClerezzaConverter(); static List<Triple> owlOntologyToClerezzaTriples(OWLOntology ontology); static org.apache.clerezza.commons.rdf.Graph owlOntologyToClerezzaGraph(OWLOntology ontology); static OWLOntology clerezzaGraphToOWLOntology(org.apache.clerezza.commons.rdf.Graph graph); static OWLOntology clerezzaGraphToOWLOntology(org.apache.clerezza.commons.rdf.Graph graph,
OWLOntologyManager ontologyManager); }### Answer:
@Test public void testOWLOntologyToTriples() { Collection<Triple> triples = OWLAPIToClerezzaConverter.owlOntologyToClerezzaTriples(ontology); for (Triple triple : triples) { log.info(triple.toString()); } } |
### Question:
StanbolNamespacePrefixService implements NamespacePrefixService, NamespacePrefixProvider { @Override public String getFullName(String shortNameOrUri) { String prefix = NamespaceMappingUtils.getPrefix(shortNameOrUri); if(prefix != null){ String namespace = getNamespace(prefix); if(namespace != null){ return namespace+shortNameOrUri.substring(prefix.length()+1); } else { return null; } } else { return shortNameOrUri; } } StanbolNamespacePrefixService(); StanbolNamespacePrefixService(File mappingFile); void importPrefixMappings(InputStream in); static NamespacePrefixService getInstance(); @Override String getNamespace(String prefix); @Override String getPrefix(String namespace); @Override List<String> getPrefixes(String namespace); @Override String setPrefix(String prefix, String namespace); @Override String getFullName(String shortNameOrUri); @Override String getShortName(String uri); }### Answer:
@Test public void testConversionMethods(){ Assert.assertEquals("http: service.getFullName("test:localname")); Assert.assertEquals("http: service.getFullName("test:localname:test")); Assert.assertEquals("http: service.getFullName("http: Assert.assertEquals("urn:example.text:localname", service.getFullName("urn_test:localname")); Assert.assertEquals("urn:example.text:localname/test", service.getFullName("urn_test:localname/test")); Assert.assertEquals("urn:example.text:localname", service.getFullName("urn:example.text:localname")); Assert.assertNull(service.getFullName("nonExistentPrefix:localname")); } |
### Question:
RunSingleSPARQL { public Map<String,String> getSPARQLprefix(){ return this.sparqlprefix; } RunSingleSPARQL(OWLOntology owl); RunSingleSPARQL(OWLOntology owl, Map<String,String> prefix); Map<String,String> getSPARQLprefix(); boolean addSPARQLprefix(String label,String prefix); boolean removeSPARQLprefix(String label); QueryExecution createSPARQLQueryExecutionFactory(String query); }### Answer:
@Test public void testGetSPARQLprefix() { Map<String,String> map = new HashMap<String,String>(); map.put("rdfs","<http: map.put("xsd","<http: map.put("owl","<http: map.put("rdf","<http: map.put("ex","<http: RunSingleSPARQL instance = new RunSingleSPARQL(owl,map); Map<String,String> expResult = map; Map<String,String> result = instance.getSPARQLprefix(); if(!result.isEmpty()){ assertEquals(expResult, result); }else{ fail("Some errors occur in getSPARQLprefix of KReSRunSPARQL."); } } |
### Question:
RunSingleSPARQL { public boolean addSPARQLprefix(String label,String prefix){ boolean ok = false; if(!sparqlprefix.containsKey(label)){ if(!prefix.contains("<")) sparqlprefix.put(label, "<"+prefix+">"); else sparqlprefix.put(label, prefix); if(sparqlprefix.containsKey(label)) if(sparqlprefix.get(label).contains(prefix)) ok = true; }else{ System.err.println("The prefix with "+label+" already exists. Prefix: "+sparqlprefix.get(label)); ok = false; } return ok; } RunSingleSPARQL(OWLOntology owl); RunSingleSPARQL(OWLOntology owl, Map<String,String> prefix); Map<String,String> getSPARQLprefix(); boolean addSPARQLprefix(String label,String prefix); boolean removeSPARQLprefix(String label); QueryExecution createSPARQLQueryExecutionFactory(String query); }### Answer:
@Test public void testAddSPARQLprefix() { String label = "mylabel"; String prefix = "<http: Map<String,String> map = new HashMap<String,String>(); map.put("rdfs","http: map.put("xsd","<http: map.put("owl","<http: map.put("rdf","<http: map.put("ex","<http: RunSingleSPARQL instance = new RunSingleSPARQL(owl,map); boolean result = instance.addSPARQLprefix(label, prefix); if(result){ Map<String, String> mymap = instance.getSPARQLprefix(); assertEquals(prefix, mymap.get(label)); }else{ fail("Some errors occur in addSPARQLprefix of KReSRunSPARQL."); } } |
### Question:
RunSingleSPARQL { public boolean removeSPARQLprefix(String label){ boolean ok = false; if(sparqlprefix.containsKey(label)){ sparqlprefix.remove(label); if(!sparqlprefix.containsKey(label)) ok = true; else ok = false; }else{ System.err.println("No prefix with name "+label); ok = false; } return ok; } RunSingleSPARQL(OWLOntology owl); RunSingleSPARQL(OWLOntology owl, Map<String,String> prefix); Map<String,String> getSPARQLprefix(); boolean addSPARQLprefix(String label,String prefix); boolean removeSPARQLprefix(String label); QueryExecution createSPARQLQueryExecutionFactory(String query); }### Answer:
@Test public void testRemoveSPARQLprefix() { Map<String,String> map = new HashMap<String,String>(); map.put("rdfs","<http: map.put("xsd","<http: map.put("owl","<http: map.put("rdf","<http: map.put("ex","<http: RunSingleSPARQL instance = new RunSingleSPARQL(owl,map); boolean result = instance.removeSPARQLprefix("ex"); if(result){ Map<String, String> mymap = instance.getSPARQLprefix(); assertEquals(false, mymap.containsKey("ex")); }else{ fail("Some errors occur in removeSPARQLprefix of KReSRunSPARQL."); } } |
### Question:
RunSingleSPARQL { public QueryExecution createSPARQLQueryExecutionFactory(String query){ if(!sparqlprefix.isEmpty()){ Iterator<String> keys = sparqlprefix.keySet().iterator(); String prefix =""; while(keys.hasNext()){ String key = keys.next(); prefix = prefix+"PREFIX "+key+": "+sparqlprefix.get(key)+"\n"; } query = prefix+query; try{ return QueryExecutionFactory.create(query,jenamodel); }catch (Exception e){ e.printStackTrace(); return null; } }else{ System.err.println("There is not prefix defined in sparqlprefix."); return null; } } RunSingleSPARQL(OWLOntology owl); RunSingleSPARQL(OWLOntology owl, Map<String,String> prefix); Map<String,String> getSPARQLprefix(); boolean addSPARQLprefix(String label,String prefix); boolean removeSPARQLprefix(String label); QueryExecution createSPARQLQueryExecutionFactory(String query); }### Answer:
@Test public void testCreateSPARQLQueryExecutionFactory() { Map<String,String> map = new HashMap<String,String>(); map.put("rdfs","<http: map.put("xsd","<http: map.put("owl","<http: map.put("rdf","<http: map.put("ex","<http: String query = "SELECT * WHERE {?p rdf:type ex:Person .}"; RunSingleSPARQL instance = new RunSingleSPARQL(owl,map); QueryExecution queryExecution = instance.createSPARQLQueryExecutionFactory(query); if (queryExecution == null) { fail("Some errors occurred in createSPARQLQueryExecutionFactory of KReSRunSPARQL"); } ResultSet result = queryExecution.execSelect(); if(result!=null){ int m = 0; while(result.hasNext()){ result.next(); m++; } queryExecution.close(); assertEquals(3, m); }else{ fail("Some errors occur in createSPARQLQueryExecutionFactory of KReSRunSPARQL"); } } |
### Question:
PermissionDefinitions { PermissionInfo[] retrievePermissions(String location) { List<PermissionInfo> permInfoList = new ArrayList<PermissionInfo>(); Iterator<Triple> ownerTriples = systemGraph.filter(new IRI(location), OSGI.owner, null); if (ownerTriples.hasNext()) { BlankNodeOrIRI user = (BlankNodeOrIRI) ownerTriples.next().getObject(); lookForPermissions(user, permInfoList); } if (permInfoList.isEmpty()) { return null; } return permInfoList.toArray(new PermissionInfo[permInfoList.size()]); } PermissionDefinitions(Graph systeGraph); }### Answer:
@Test public void testAllowedBundle() { PermissionInfo[] permInfos = this.permissionDefinitions .retrievePermissions("file: List<PermissionInfo> permInfoList = Arrays.asList(permInfos); List<PermissionInfo> expectedPermInfos = Arrays.asList(allPermissions); Assert.assertTrue(permInfoList.containsAll(expectedPermInfos)); Assert.assertTrue(expectedPermInfos.containsAll(permInfoList)); }
@Test public void testUnknownBundle() { Assert.assertNotSame(allPermissions, this.permissionDefinitions .retrievePermissions("file: Assert.assertArrayEquals(nullPermission, this.permissionDefinitions .retrievePermissions("file: } |
### Question:
SimpleLabelTokenizer implements LabelTokenizer { @Override public String[] tokenize(String label, String language) { if(label == null){ throw new IllegalArgumentException("The parsed Label MUST NOT be NULL!"); } ArrayList<String> tokens = new ArrayList<String>(); int start = -1; int pc = 0; CT state = CT.WHITESPACE; CT charType = CT.WHITESPACE; for (int i = 0; i < label.length(); i++) { int c = label.codePointAt(i); charType = getType(c); if (state == CT.WHITESPACE) { if (charType != CT.WHITESPACE) { start = i; } } else { if (charType != state || charType == CT.OTHER && c != pc) { tokens.add(label.substring(start, i)); start = i; } } state = charType; pc = c; } if (charType != CT.WHITESPACE) { tokens.add(label.substring(start, label.length())); } return tokens.toArray(new String[tokens.size()]); } @Override String[] tokenize(String label, String language); }### Answer:
@Test(expected=IllegalArgumentException.class) public void testNullLabel(){ tokenizer.tokenize(null, "en"); }
@Test public void testNullLanguate(){ String[] tokens = tokenizer.tokenize(label, null); Assert.assertNotNull(tokens); Assert.assertArrayEquals(expected, tokens); }
@Test public void testTokenizer(){ String[] tokens = tokenizer.tokenize(label, "en"); Assert.assertNotNull(tokens); Assert.assertArrayEquals(expected, tokens); }
@Test public void testEmptyLabel(){ String[] tokens = tokenizer.tokenize("", "en"); Assert.assertNotNull(tokens); Assert.assertTrue(tokens.length == 0); } |
### Question:
OpenNlpLabelTokenizer implements LabelTokenizer { @Override public String[] tokenize(String label, String language) { if(label == null){ throw new IllegalArgumentException("The parsed Label MUST NOT be NULL!"); } if(languageConfig.isLanguage(language)){ String modelName = languageConfig.getParameter(language, PARAM_MODEL); if(modelName != null){ try { TokenizerModel model = openNlp.getModel(TokenizerModel.class, modelName, null); return new TokenizerME(model).tokenize(label); } catch (Exception e) { log.warn("Unable to load configured TokenizerModel '"+modelName + "' for language '"+language + "! Fallback to default Tokenizers",e); } } return openNlp.getTokenizer(language).tokenize(label); } else { return null; } } OpenNlpLabelTokenizer(); OpenNlpLabelTokenizer(OpenNLP openNLP); @Override String[] tokenize(String label, String language); static final String PARAM_MODEL; }### Answer:
@Test(expected=IllegalArgumentException.class) public void testNullLabel(){ tokenizer.tokenize(null, "en"); }
@Test public void testNullLanguage(){ String[] tokens = tokenizer.tokenize(label, null); Assert.assertNotNull(tokens); Assert.assertArrayEquals(expected, tokens); }
@Test public void testTokenizer(){ String[] tokens = tokenizer.tokenize(label, "en"); Assert.assertNotNull(tokens); Assert.assertArrayEquals(expected, tokens); }
@Test public void testEmptyLabel(){ String[] tokens = tokenizer.tokenize("", "en"); Assert.assertNotNull(tokens); Assert.assertTrue(tokens.length == 0); } |
### Question:
MetaxaCore { public Model extract( InputStream in, URIImpl docId, String mimeType) throws ExtractorException, IOException { @SuppressWarnings("rawtypes") Set factories = this.extractorRegistry.getExtractorFactories(mimeType); Model result = null; if (factories != null && !factories.isEmpty()) { ExtractorFactory factory = (ExtractorFactory)factories.iterator().next(); Extractor extractor = factory.get(); RDFContainerFactory containerFactory = new RDFContainerFactoryImpl(); RDFContainer container = containerFactory.getRDFContainer(docId); extractor.extract( container.getDescribedUri(), new BufferedInputStream(in, 8192), null, mimeType, container); in.close(); result = container.getModel(); } return result; } MetaxaCore(String configFileName); boolean isSupported(String mimeType); Model extract(
InputStream in, URIImpl docId, String mimeType); static String getText(Model model); }### Answer:
@Test public void testMailExtraction() throws Exception { String testFile = "mail-multipart-test.eml"; InputStream in = getResourceAsStream(testFile); assertNotNull("failed to load resource " + testFile, in); Model m = extractor.extract(in, new URIImpl("file: boolean textContained = m.contains(Variable.ANY, NMO.plainTextMessageContent, Variable.ANY); assertTrue(textContained); } |
### Question:
HermitReasoningService extends AbstractOWLApiReasoningService implements OWLApiReasoningService { @Override protected OWLReasoner getReasoner(OWLOntology ontology) { log.debug("Creating HermiT reasoner: {}",ontology); Configuration config = new Configuration(); config.ignoreUnsupportedDatatypes = true; config.throwInconsistentOntologyException = true; log.debug("Configuration: {}, debugger {}",config,config.monitor); ReasonerFactory risfactory = new ReasonerFactory(); log.debug("factory: {}",risfactory); OWLReasoner reasoner = null; reasoner = risfactory.createReasoner(ontology, config); log.debug("Reasoner : {}",reasoner); if(reasoner == null){ log.error("Cannot create the reasner!!"); throw new IllegalArgumentException("Cannot create the reasoner"); } return reasoner; } @Override String getPath(); @Activate void activate(ComponentContext context); static final String _DEFAULT_PATH; }### Answer:
@Test public void testInstantiation() { log.info("Testing the innstantiation of an HermitReasoningService"); OWLOntology foaf = TestData.manager.getOntology(IRI.create(TestData.FOAF_NS)); HermitReasoningService akindofhermit = new HermitReasoningService() { protected OWLReasoner getReasoner(OWLOntology ontology) { try { OWLReasoner reasoner = super.getReasoner(ontology); assertTrue(reasoner != null); return reasoner; } catch (Throwable t) { log.error( "Some prolem occurred while instantiating the HermitReasoningService. Message was: {}", t.getLocalizedMessage()); assertTrue(false); return null; } } }; long startHere = System.currentTimeMillis(); akindofhermit.getReasoner(foaf); long endHere = System.currentTimeMillis(); log.info("Instantiating an Hermit reasoner lasts {} milliseconds", (endHere - startHere)); } |
### Question:
JerseyUtils { public static boolean testParameterizedType(Class<?> rawType, Class<?>[] parameterTypes, Type type) { if (!testType(rawType, type)) { return false; } while (type != null) { Type[] parameters = null; if (type instanceof ParameterizedType) { parameters = ((ParameterizedType) type).getActualTypeArguments(); if (parameters.length == parameterTypes.length) { boolean compatible = true; for (int i = 0; compatible && i < parameters.length; i++) { compatible = testType(parameterTypes[i], parameters[i]); } if (compatible) { return true; } } } if (type instanceof Class<?>) { type = ((Class<?>) type).getGenericSuperclass(); } else { return false; } } return false; } private JerseyUtils(); static FieldQuery createFieldQueryForFindRequest(String name, String field,
String language, Integer limit,
Integer offset, String ldpath); static boolean testType(Class<?> required, Type type); static boolean testParameterizedType(Class<?> rawType, Class<?>[] parameterTypes, Type type); static Map<String,String> parseForm(InputStream entityStream,String charset); static final Set<String> REPRESENTATION_SUPPORTED_MEDIA_TYPES; static final Set<String> ENTITY_SUPPORTED_MEDIA_TYPES; static final Set<String> QUERY_RESULT_SUPPORTED_MEDIA_TYPES; }### Answer:
@Test public void testParameterisedType() { Assert.assertTrue(JerseyUtils.testParameterizedType(Map.class, new Class[]{String.class,Collection.class}, TestMap.class)); } |
### Question:
SparqlQueryUtils { protected static final String getGrammarEscapedValue(String value){ StringBuilder sb = new StringBuilder(value.length()+4); addGrammarEscapedValue(sb, value); return sb.toString(); } private SparqlQueryUtils(); static String createSparqlConstructQuery(SparqlFieldQuery query,
SparqlEndpointTypeEnum endpointType,
String... additionalFields); static String createSparqlConstructQuery(SparqlFieldQuery query,
int limit,
SparqlEndpointTypeEnum endpointType,
String... additionalFields); static String createSparqlSelectQuery(SparqlFieldQuery query, SparqlEndpointTypeEnum endpointType); static String createSparqlSelectQuery(SparqlFieldQuery query,
int limit,
SparqlEndpointTypeEnum endpointType); static String createSparqlSelectQuery(SparqlFieldQuery query,
boolean includeFields,
SparqlEndpointTypeEnum endpointType); static String createSparqlSelectQuery(SparqlFieldQuery query,
boolean includeFields,
int limit,
SparqlEndpointTypeEnum endpointType); static String guessXsdType(Class<?> javaClass); static void main(String[] args); }### Answer:
@Test public void testGrammarEncodning(){ assertEquals("test\\'s",SparqlQueryUtils.getGrammarEscapedValue("test's")); assertEquals("test\\\"s",SparqlQueryUtils.getGrammarEscapedValue("test\"s")); assertEquals("new\\\nline",SparqlQueryUtils.getGrammarEscapedValue("new\nline")); } |
### Question:
RdfValueFactory implements ValueFactory { public RdfRepresentation createRdfRepresentation(IRI node, Graph graph) { if (node == null) { throw new IllegalArgumentException("The parsed id MUST NOT be NULL!"); } if(graph == null){ throw new IllegalArgumentException("The parsed graph MUST NOT be NULL!"); } return new RdfRepresentation(node, graph); } private RdfValueFactory(); RdfValueFactory(Graph graph); static RdfValueFactory getInstance(); @Override RdfReference createReference(Object value); @Override RdfText createText(Object value); @Override RdfText createText(String text, String language); @Override RdfRepresentation createRepresentation(String id); RdfRepresentation createRdfRepresentation(IRI node, Graph graph); RdfRepresentation toRdfRepresentation(Representation representation); }### Answer:
@Test(expected=IllegalArgumentException.class) public void testNullNodeRepresentation() { Graph graph = new IndexedGraph(); valueFactory.createRdfRepresentation(null, graph); }
@Test(expected=IllegalArgumentException.class) public void testNullGraphRepresentation() { IRI rootNode = new IRI("urn:test.rootNode"); valueFactory.createRdfRepresentation(rootNode, null); } |
### Question:
TripleMatcherImpl implements TripleMatcher { @Override public boolean matches(Triple t) { return objectUri != null && t.getPredicate().equals(predicateUri) && t.getObject().equals(objectUri) ; } TripleMatcherImpl(String line); @Override String toString(); String getExpression(); @Override boolean matches(Triple t); }### Answer:
@Test public void testMatches() throws Exception { final TripleMatcherImpl m = new TripleMatcherImpl("FOO URI BAR"); assertTrue(m.matches(TripleUtil.uriTriple("me","FOO","BAR"))); assertTrue(m.matches(TripleUtil.uriTriple("you","FOO","BAR"))); assertFalse(m.matches(TripleUtil.uriTriple("me","wii","BAR"))); assertFalse(m.matches(TripleUtil.uriTriple("me","FOO","wii"))); } |
### Question:
NIFHelper { public static final IRI getNifFragmentURI(IRI base, int start,int end){ if(base == null){ throw new IllegalArgumentException("Base URI MUST NOT be NULL!"); } StringBuilder sb = new StringBuilder(base.getUnicodeString()); sb.append("#char="); sb.append(start >= 0 ? start : 0).append(','); if(end >= 0){ if(end < start){ throw new IllegalArgumentException("End index '"+end+"' < start '"+start+"'!"); } sb.append(end); } return new IRI(sb.toString()); } private NIFHelper(); static final IRI getNifFragmentURI(IRI base, int start,int end); static final IRI getNifOffsetURI(IRI base, int start, int end); static final IRI getNifHashURI(IRI base, int start, int end, String text); static IRI writeSpan(Graph graph, IRI base, AnalysedText text, Language language, Span span); static void writePos(Graph graph, Annotated annotated, IRI segmentUri); static void writePhrase(Graph graph, Annotated annotated, IRI segmentUri); static final Map<SpanTypeEnum,IRI> SPAN_TYPE_TO_SSO_TYPE; static final Map<LexicalCategory,IRI> LEXICAL_TYPE_TO_PHRASE_TYPE; static final int NIF_HASH_CONTEXT_LENGTH; static final int NIF_HASH_MAX_STRING_LENGTH; static final Charset UTF8; }### Answer:
@Test public void testFragmentURI(){ Assert.assertEquals( new IRI(base.getUnicodeString()+"#char=23,26"), NIFHelper.getNifFragmentURI(base, 23, 26)); } |
### Question:
NIFHelper { public static final IRI getNifOffsetURI(IRI base, int start, int end){ if(base == null){ throw new IllegalArgumentException("Base URI MUST NOT be NULL!"); } StringBuilder sb = new StringBuilder(base.getUnicodeString()); sb.append("#offset_"); sb.append(start >= 0 ? start : 0).append('_'); if(end >= 0){ if(end < start){ throw new IllegalArgumentException("End index '"+end+"' < start '"+start+"'!"); } sb.append(end); } return new IRI(sb.toString()); } private NIFHelper(); static final IRI getNifFragmentURI(IRI base, int start,int end); static final IRI getNifOffsetURI(IRI base, int start, int end); static final IRI getNifHashURI(IRI base, int start, int end, String text); static IRI writeSpan(Graph graph, IRI base, AnalysedText text, Language language, Span span); static void writePos(Graph graph, Annotated annotated, IRI segmentUri); static void writePhrase(Graph graph, Annotated annotated, IRI segmentUri); static final Map<SpanTypeEnum,IRI> SPAN_TYPE_TO_SSO_TYPE; static final Map<LexicalCategory,IRI> LEXICAL_TYPE_TO_PHRASE_TYPE; static final int NIF_HASH_CONTEXT_LENGTH; static final int NIF_HASH_MAX_STRING_LENGTH; static final Charset UTF8; }### Answer:
@Test public void testOffsetURI(){ Assert.assertEquals( base.getUnicodeString()+"#offset_23_26", NIFHelper.getNifOffsetURI(base, 23, 26).getUnicodeString()); } |
### Question:
LanguageConfiguration { public void setConfiguration(Dictionary<?,?> configuration) throws ConfigurationException { processConfiguration(configuration.get(property)); } @SuppressWarnings("unchecked") LanguageConfiguration(String property, String[] defaultConfig); String getProperty(); void setConfiguration(Dictionary<?,?> configuration); void setConfiguration(ServiceReference ref); boolean isLanguage(String language); Set<String> getExplicitlyIncluded(); Set<String> getExplicitlyExcluded(); boolean useWildcard(); Map<String,String> getParameters(String parsedLang); Map<String,String> getLanguageParams(String parsedLang); Map<String,String> getDefaultParameters(); void setDefault(); String getParameter(String language, String paramName); }### Answer:
@Test(expected=ConfigurationException.class) public void testParamsOnExcludedLanguage() throws ConfigurationException { LanguageConfiguration lc = new LanguageConfiguration("test", null); Dictionary<String,Object> config = new Hashtable<String,Object>(); config.put("test", "*,!de;param=notAllowed"); lc.setConfiguration(config); }
@Test(expected=ConfigurationException.class) public void testParamsIncludedAndExcludedLanguage() throws ConfigurationException { LanguageConfiguration lc = new LanguageConfiguration("test", null); Dictionary<String,Object> config = new Hashtable<String,Object>(); config.put("test", "de,ru,!de"); lc.setConfiguration(config); } |
### Question:
OfferService { public Iterable<Offer> findAllTheOffersOfAProduct(final long productId) { return offerRepository.findAllByProductId(productId); } Iterable<Offer> findAllTheOffersOfAProduct(final long productId); }### Answer:
@Test public void shouldReturnTheOffersOfAProduct() { long productId = 1; List<Offer> offers = OfferFactory.getOffers(productId, 5); when(offerRepository.findAllByProductId(productId)).thenReturn(offers); assertThat(offerService.findAllTheOffersOfAProduct(productId)).isEqualTo(offers); } |
### Question:
OfferController { @RequestMapping(path = "/product/{product}", method = RequestMethod.GET) public Iterable<Offer> getProductOffers(@PathVariable("product") long productId) { return offerService.findAllTheOffersOfAProduct(productId); } @RequestMapping(path = "/product/{product}", method = RequestMethod.GET) Iterable<Offer> getProductOffers(@PathVariable("product") long productId); }### Answer:
@Test public void shouldReturnTheOffersOfAProduct() { long productId = 1; List<Offer> offers = OfferFactory.getOffers(productId, 5); when(offerService.findAllTheOffersOfAProduct(productId)).thenReturn(offers); assertThat(offerController.getProductOffers(productId)).isEqualTo(offers); } |
### Question:
CategoryService { public Iterable<Category> findAll() { return categoryRepository.findAll(); } Iterable<Category> findAll(); }### Answer:
@Test public void shouldReturnTheCategories() { List<Category> categories = TestDataFactory.getCategories(6); when(categoryRepository.findAll()).thenReturn(categories); assertThat(categoryService.findAll()).isEqualTo(categories); } |
### Question:
ProductService { public Optional<Product> findProductById(final long productId) { return productRepository.findById(productId); } Optional<Product> findProductById(final long productId); Iterable<Product> findProductsByCategoryId(long categoryId); }### Answer:
@Test public void shouldFindAProductByItsId() { long productId = 1; Product product = TestDataFactory.getProduct(productId); when(productRepository.findById(productId)).thenReturn(Optional.of(product)); assertThat(productService.findProductById(productId).orElse(null)).isEqualTo(product); } |
### Question:
ProductService { public Iterable<Product> findProductsByCategoryId(long categoryId) { return categoryRepository.findById(categoryId) .map(productRepository::findAllByCategory) .orElse(Collections.emptyList()); } Optional<Product> findProductById(final long productId); Iterable<Product> findProductsByCategoryId(long categoryId); }### Answer:
@Test public void shouldFindAllTheProductsByTheCategoryId() { long categoryId = 1; Category category = TestDataFactory.getCategory(categoryId); List<Product> products = TestDataFactory.getProductList(5, category); when(categoryRepository.findById(categoryId)).thenReturn(Optional.of(category)); when(productRepository.findAllByCategory(category)).thenReturn(products); assertThat(productService.findProductsByCategoryId(categoryId)).isEqualTo(products); } |
### Question:
ProductController { @RequestMapping(path = "/{productId}", method = RequestMethod.GET) public Product getProductDetail(@PathVariable("productId") long productId) { return productService.findProductById(productId).orElse(null); } @RequestMapping(path = "/{productId}", method = RequestMethod.GET) Product getProductDetail(@PathVariable("productId") long productId); @RequestMapping(method = RequestMethod.GET) Iterable<Product> getProducts(@RequestParam("category") long categoryId); }### Answer:
@Test public void shouldReturnAProduct() { long productId = 1; Product product = TestDataFactory.getProduct(productId); when(productService.findProductById(productId)).thenReturn(Optional.of(product)); assertThat(productController.getProductDetail(productId)).isEqualTo(product); } |
### Question:
ProductController { @RequestMapping(method = RequestMethod.GET) public Iterable<Product> getProducts(@RequestParam("category") long categoryId) { return productService.findProductsByCategoryId(categoryId); } @RequestMapping(path = "/{productId}", method = RequestMethod.GET) Product getProductDetail(@PathVariable("productId") long productId); @RequestMapping(method = RequestMethod.GET) Iterable<Product> getProducts(@RequestParam("category") long categoryId); }### Answer:
@Test public void shouldReturnTheProductsOfACategory() { long categoryId = 1; List<Product> products = TestDataFactory.getProductList(5, categoryId); when(productService.findProductsByCategoryId(categoryId)).thenReturn(products); assertThat(productController.getProducts(categoryId)).isEqualTo(products); } |
### Question:
CategoryController { @RequestMapping(method = RequestMethod.GET) public Iterable<Category> getCategories() { return categoryService.findAll(); } @RequestMapping(method = RequestMethod.GET) Iterable<Category> getCategories(); }### Answer:
@Test public void shouldReturnTheCategories() { List<Category> categories = TestDataFactory.getCategories(6); when(categoryService.findAll()).thenReturn(categories); assertThat(categoryController.getCategories()).isEqualTo(categories); } |
### Question:
AdminOrderController { @PostMapping(value = "/adminorder") public HttpEntity addOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers) { return ok(adminOrderService.addOrder(request, headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/adminorder") HttpEntity getAllOrders(@RequestHeader HttpHeaders headers); @PostMapping(value = "/adminorder") HttpEntity addOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers); @PutMapping(value = "/adminorder") HttpEntity updateOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers); @DeleteMapping(value = "/adminorder/{orderId}/{trainNumber}") HttpEntity deleteOrder(@PathVariable String orderId, @PathVariable String trainNumber, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testAddOrder() throws Exception { Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); Mockito.when(adminOrderService.addOrder(Mockito.any(Order.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(order); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/adminorderservice/adminorder").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
AdminOrderController { @PutMapping(value = "/adminorder") public HttpEntity updateOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers) { return ok(adminOrderService.updateOrder(request, headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/adminorder") HttpEntity getAllOrders(@RequestHeader HttpHeaders headers); @PostMapping(value = "/adminorder") HttpEntity addOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers); @PutMapping(value = "/adminorder") HttpEntity updateOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers); @DeleteMapping(value = "/adminorder/{orderId}/{trainNumber}") HttpEntity deleteOrder(@PathVariable String orderId, @PathVariable String trainNumber, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testUpdateOrder() throws Exception { Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); Mockito.when(adminOrderService.updateOrder(Mockito.any(Order.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(order); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/adminorderservice/adminorder").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
AdminOrderController { @DeleteMapping(value = "/adminorder/{orderId}/{trainNumber}") public HttpEntity deleteOrder(@PathVariable String orderId, @PathVariable String trainNumber, @RequestHeader HttpHeaders headers) { return ok(adminOrderService.deleteOrder(orderId, trainNumber, headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/adminorder") HttpEntity getAllOrders(@RequestHeader HttpHeaders headers); @PostMapping(value = "/adminorder") HttpEntity addOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers); @PutMapping(value = "/adminorder") HttpEntity updateOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers); @DeleteMapping(value = "/adminorder/{orderId}/{trainNumber}") HttpEntity deleteOrder(@PathVariable String orderId, @PathVariable String trainNumber, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testDeleteOrder() throws Exception { Mockito.when(adminOrderService.deleteOrder(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/adminorderservice/adminorder/orderId/trainNumber")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
CancelServiceImpl implements CancelService { public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[Cancel Order Service][Send Email]"); HttpEntity requestEntity = new HttpEntity(notifyInfo, headers); ResponseEntity<Boolean> re = restTemplate.exchange( "http: HttpMethod.POST, requestEntity, Boolean.class); return re.getBody(); } @Override Response cancelOrder(String orderId, String loginId, HttpHeaders headers); boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders headers); @Override Response calculateRefund(String orderId, HttpHeaders headers); boolean drawbackMoney(String money, String userId, HttpHeaders headers); Response<User> getAccount(String orderId, HttpHeaders headers); }### Answer:
@Test public void testSendEmail() { NotifyInfo notifyInfo = new NotifyInfo(); HttpEntity requestEntity2 = new HttpEntity(notifyInfo, headers); ResponseEntity<Boolean> re = new ResponseEntity<>(true, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.POST, requestEntity2, Boolean.class)).thenReturn(re); Boolean result = cancelServiceImpl.sendEmail(notifyInfo, headers); Assert.assertTrue(result); } |
### Question:
CancelServiceImpl implements CancelService { public boolean drawbackMoney(String money, String userId, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[Cancel Order Service][Draw Back Money] Draw back money..."); HttpEntity requestEntity = new HttpEntity(headers); ResponseEntity<Response> re = restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class); Response result = re.getBody(); return result.getStatus() == 1; } @Override Response cancelOrder(String orderId, String loginId, HttpHeaders headers); boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders headers); @Override Response calculateRefund(String orderId, HttpHeaders headers); boolean drawbackMoney(String money, String userId, HttpHeaders headers); Response<User> getAccount(String orderId, HttpHeaders headers); }### Answer:
@Test public void testDrawbackMoney() { Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Boolean result = cancelServiceImpl.drawbackMoney("money", "userId", headers); Assert.assertTrue(result); } |
### Question:
CancelServiceImpl implements CancelService { public Response<User> getAccount(String orderId, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[Cancel Order Service][Get By Id]"); HttpEntity requestEntity = new HttpEntity( headers); ResponseEntity<Response<User>> re = restTemplate.exchange( "http: HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<User>>() { }); return re.getBody(); } @Override Response cancelOrder(String orderId, String loginId, HttpHeaders headers); boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders headers); @Override Response calculateRefund(String orderId, HttpHeaders headers); boolean drawbackMoney(String money, String userId, HttpHeaders headers); Response<User> getAccount(String orderId, HttpHeaders headers); }### Answer:
@Test public void testGetAccount() { Response<User> response = new Response<>(); ResponseEntity<Response<User>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<User>>() { })).thenReturn(re); Response<User> result = cancelServiceImpl.getAccount("orderId", headers); Assert.assertEquals(new Response<User>(null, null, null), result); } |
### Question:
CancelController { @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ Cancel Service ] !"; } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/refound/{orderId}") HttpEntity calculate(@PathVariable String orderId, @RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/{orderId}/{loginId}") HttpEntity cancelTicket(@PathVariable String orderId, @PathVariable String loginId,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/cancelservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Cancel Service ] !")); } |
### Question:
CancelController { @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/refound/{orderId}") public HttpEntity calculate(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { CancelController.LOGGER.info("[Cancel Order Service][Calculate Cancel Refund] OrderId: {}", orderId); return ok(cancelService.calculateRefund(orderId, headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/refound/{orderId}") HttpEntity calculate(@PathVariable String orderId, @RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/{orderId}/{loginId}") HttpEntity cancelTicket(@PathVariable String orderId, @PathVariable String loginId,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testCalculate() throws Exception { Mockito.when(cancelService.calculateRefund(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/cancelservice/cancel/refound/order_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
CancelController { @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/{orderId}/{loginId}") public HttpEntity cancelTicket(@PathVariable String orderId, @PathVariable String loginId, @RequestHeader HttpHeaders headers) { CancelController.LOGGER.info("[Cancel Order Service][Cancel Ticket] info: {}", orderId); try { CancelController.LOGGER.info("[Cancel Order Service][Cancel Ticket] Verify Success"); return ok(cancelService.cancelOrder(orderId, loginId, headers)); } catch (Exception e) { LOGGER.error(e.getMessage()); return null; } } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/refound/{orderId}") HttpEntity calculate(@PathVariable String orderId, @RequestHeader HttpHeaders headers); @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/{orderId}/{loginId}") HttpEntity cancelTicket(@PathVariable String orderId, @PathVariable String loginId,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testCancelTicket() throws Exception { Mockito.when(cancelService.cancelOrder(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/cancelservice/cancel/order_id/login_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
InsidePaymentServiceImpl implements InsidePaymentService { @Override public Response queryAddMoney(HttpHeaders headers) { List<Money> monies = addMoneyRepository.findAll(); if (monies != null && !monies.isEmpty()) { return new Response<>(1, "Query Money Success", null); } else { return new Response<>(0, "", null); } } @Override Response pay(PaymentInfo info, HttpHeaders headers); @Override Response createAccount(AccountInfo info, HttpHeaders headers); @Override Response addMoney(String userId, String money, HttpHeaders headers); @Override Response queryAccount(HttpHeaders headers); String queryAccount(String userId, HttpHeaders headers); @Override Response queryPayment(HttpHeaders headers); @Override Response drawBack(String userId, String money, HttpHeaders headers); @Override Response payDifference(PaymentInfo info, HttpHeaders headers); @Override Response queryAddMoney(HttpHeaders headers); @Override void initPayment(Payment payment, HttpHeaders headers); @Autowired
public AddMoneyRepository addMoneyRepository; @Autowired
public PaymentRepository paymentRepository; @Autowired
public RestTemplate restTemplate; }### Answer:
@Test public void testQueryAddMoney1() { List<Money> monies = new ArrayList<>(); monies.add(new Money()); Mockito.when(addMoneyRepository.findAll()).thenReturn(monies); Response result = insidePaymentServiceImpl.queryAddMoney(headers); Assert.assertEquals(new Response<>(1, "Query Money Success", null), result); }
@Test public void testQueryAddMoney2() { Mockito.when(addMoneyRepository.findAll()).thenReturn(null); Response result = insidePaymentServiceImpl.queryAddMoney(headers); Assert.assertEquals(new Response<>(0, "", null), result); } |
### Question:
InsidePaymentServiceImpl implements InsidePaymentService { @Override public void initPayment(Payment payment, HttpHeaders headers) { Payment paymentTemp = paymentRepository.findById(payment.getId()); if (paymentTemp == null) { paymentRepository.save(payment); } else { InsidePaymentServiceImpl.LOGGER.info("[Inside Payment Service][Init Payment] Already Exists: {}", payment.getId()); } } @Override Response pay(PaymentInfo info, HttpHeaders headers); @Override Response createAccount(AccountInfo info, HttpHeaders headers); @Override Response addMoney(String userId, String money, HttpHeaders headers); @Override Response queryAccount(HttpHeaders headers); String queryAccount(String userId, HttpHeaders headers); @Override Response queryPayment(HttpHeaders headers); @Override Response drawBack(String userId, String money, HttpHeaders headers); @Override Response payDifference(PaymentInfo info, HttpHeaders headers); @Override Response queryAddMoney(HttpHeaders headers); @Override void initPayment(Payment payment, HttpHeaders headers); @Autowired
public AddMoneyRepository addMoneyRepository; @Autowired
public PaymentRepository paymentRepository; @Autowired
public RestTemplate restTemplate; }### Answer:
@Test public void testInitPayment1() { Payment payment = new Payment(); Mockito.when(paymentRepository.findById(Mockito.anyString())).thenReturn(null); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); insidePaymentServiceImpl.initPayment(payment, headers); Mockito.verify(paymentRepository, times(1)).save(Mockito.any(Payment.class)); }
@Test public void testInitPayment2() { Payment payment = new Payment(); Mockito.when(paymentRepository.findById(Mockito.anyString())).thenReturn(payment); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); insidePaymentServiceImpl.initPayment(payment, headers); Mockito.verify(paymentRepository, times(0)).save(Mockito.any(Payment.class)); } |
### Question:
InsidePaymentController { @GetMapping(path = "/welcome") public String home() { return "Welcome to [ InsidePayment Service ] !"; } @GetMapping(path = "/welcome") String home(); @PostMapping(value = "/inside_payment") HttpEntity pay(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/account") HttpEntity createAccount(@RequestBody AccountInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/{userId}/{money}") HttpEntity addMoney(@PathVariable String userId, @PathVariable
String money, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/payment") HttpEntity queryPayment(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/account") HttpEntity queryAccount(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/drawback/{userId}/{money}") HttpEntity drawBack(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/difference") HttpEntity payDifference(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/money") HttpEntity queryAddMoney(@RequestHeader HttpHeaders headers); @Autowired
public InsidePaymentService service; }### Answer:
@Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ InsidePayment Service ] !")); } |
### Question:
PreserveServiceImpl implements PreserveService { public Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders) { Seat seatRequest = new Seat(); seatRequest.setTravelDate(date); seatRequest.setTrainNumber(tripId); seatRequest.setStartStation(startStationId); seatRequest.setDestStation(endStataionId); seatRequest.setSeatType(seatType); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, httpHeaders); ResponseEntity<Response<Ticket>> reTicket = restTemplate.exchange( "http: HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { }); return reTicket.getBody().getData(); } @Override Response preserve(OrderTicketsInfo oti, HttpHeaders headers); Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders); boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders); User getAccount(String accountId, HttpHeaders httpHeaders); }### Answer:
@Test public void testDipatchSeat() { long mills = System.currentTimeMillis(); Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, headers); Response<Ticket> response = new Response<>(); ResponseEntity<Response<Ticket>> reTicket = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { })).thenReturn(reTicket); Ticket result = preserveServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); Assert.assertNull(result); } |
### Question:
PreserveServiceImpl implements PreserveService { public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Service][Send Email]"); HttpEntity requestEntitySendEmail = new HttpEntity(notifyInfo, httpHeaders); ResponseEntity<Boolean> reSendEmail = restTemplate.exchange( "http: HttpMethod.POST, requestEntitySendEmail, Boolean.class); return reSendEmail.getBody(); } @Override Response preserve(OrderTicketsInfo oti, HttpHeaders headers); Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders); boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders); User getAccount(String accountId, HttpHeaders httpHeaders); }### Answer:
@Test public void testSendEmail() { NotifyInfo notifyInfo = new NotifyInfo(); HttpEntity requestEntitySendEmail = new HttpEntity(notifyInfo, headers); ResponseEntity<Boolean> reSendEmail = new ResponseEntity<>(true, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.POST, requestEntitySendEmail, Boolean.class)).thenReturn(reSendEmail); boolean result = preserveServiceImpl.sendEmail(notifyInfo, headers); Assert.assertTrue(result); } |
### Question:
PreserveServiceImpl implements PreserveService { public User getAccount(String accountId, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Cancel Order Service][Get Order By Id]"); HttpEntity requestEntitySendEmail = new HttpEntity(httpHeaders); ResponseEntity<Response<User>> getAccount = restTemplate.exchange( "http: HttpMethod.GET, requestEntitySendEmail, new ParameterizedTypeReference<Response<User>>() { }); Response<User> result = getAccount.getBody(); return result.getData(); } @Override Response preserve(OrderTicketsInfo oti, HttpHeaders headers); Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders); boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders); User getAccount(String accountId, HttpHeaders httpHeaders); }### Answer:
@Test public void testGetAccount() { Response<User> response = new Response<>(); ResponseEntity<Response<User>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<User>>() { })).thenReturn(re); User result = preserveServiceImpl.getAccount("1", headers); Assert.assertNull(result); } |
### Question:
PreserveController { @GetMapping(path = "/welcome") public String home() { return "Welcome to [ Preserve Service ] !"; } @GetMapping(path = "/welcome") String home(); @CrossOrigin(origins = "*") @PostMapping(value = "/preserve") HttpEntity preserve(@RequestBody OrderTicketsInfo oti,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/preserveservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Preserve Service ] !")); } |
### Question:
PreserveController { @CrossOrigin(origins = "*") @PostMapping(value = "/preserve") public HttpEntity preserve(@RequestBody OrderTicketsInfo oti, @RequestHeader HttpHeaders headers) { PreserveController.LOGGER.info("[Preserve Service][Preserve] Account order from {} -----> {} at {}", oti.getFrom(), oti.getTo(), oti.getDate()); return ok(preserveService.preserve(oti, headers)); } @GetMapping(path = "/welcome") String home(); @CrossOrigin(origins = "*") @PostMapping(value = "/preserve") HttpEntity preserve(@RequestBody OrderTicketsInfo oti,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testPreserve() throws Exception { OrderTicketsInfo oti = new OrderTicketsInfo(); Mockito.when(preserveService.preserve(Mockito.any(OrderTicketsInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(oti); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/preserveservice/preserve").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
BasicServiceImpl implements BasicService { @Override public Response queryForStationId(String stationName, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[Basic Information Service][Query For Station Id] Station Id: {}", stationName); HttpEntity requestEntity = new HttpEntity( headers); ResponseEntity<Response> re = restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class); return re.getBody(); } @Override Response queryForTravel(Travel info, HttpHeaders headers); @Override Response queryForStationId(String stationName, HttpHeaders headers); boolean checkStationExists(String stationName, HttpHeaders headers); TrainType queryTrainType(String trainTypeId, HttpHeaders headers); }### Answer:
@Test public void testQueryForStationId() { Response response = new Response<>(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Response result = basicServiceImpl.queryForStationId("stationName", headers); Assert.assertEquals(new Response<>(null, null, null), result); } |
### Question:
BasicServiceImpl implements BasicService { public boolean checkStationExists(String stationName, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[Basic Information Service][Check Station Exists] Station Name: {}", stationName); HttpEntity requestEntity = new HttpEntity( headers); ResponseEntity<Response> re = restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class); Response exist = re.getBody(); return exist.getStatus() == 1; } @Override Response queryForTravel(Travel info, HttpHeaders headers); @Override Response queryForStationId(String stationName, HttpHeaders headers); boolean checkStationExists(String stationName, HttpHeaders headers); TrainType queryTrainType(String trainTypeId, HttpHeaders headers); }### Answer:
@Test public void testCheckStationExists() { Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Boolean result = basicServiceImpl.checkStationExists("stationName", headers); Assert.assertTrue(result); } |
### Question:
BasicServiceImpl implements BasicService { public TrainType queryTrainType(String trainTypeId, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[Basic Information Service][Query Train Type] Train Type: {}", trainTypeId); HttpEntity requestEntity = new HttpEntity( headers); ResponseEntity<Response> re = restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class); Response response = re.getBody(); return JsonUtils.conveterObject(response.getData(), TrainType.class); } @Override Response queryForTravel(Travel info, HttpHeaders headers); @Override Response queryForStationId(String stationName, HttpHeaders headers); boolean checkStationExists(String stationName, HttpHeaders headers); TrainType queryTrainType(String trainTypeId, HttpHeaders headers); }### Answer:
@Test public void testQueryTrainType() { Response response = new Response<>(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); TrainType result = basicServiceImpl.queryTrainType("trainTypeId", headers); Assert.assertNull(result); } |
### Question:
BasicController { @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ Basic Service ] !"; } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @PostMapping(value = "/basic/travel") HttpEntity queryForTravel(@RequestBody Travel info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/basic/{stationName}") HttpEntity queryForStationId(@PathVariable String stationName, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/basicservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Basic Service ] !")); } |
### Question:
BasicController { @PostMapping(value = "/basic/travel") public HttpEntity queryForTravel(@RequestBody Travel info, @RequestHeader HttpHeaders headers) { return ok(service.queryForTravel(info, headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @PostMapping(value = "/basic/travel") HttpEntity queryForTravel(@RequestBody Travel info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/basic/{stationName}") HttpEntity queryForStationId(@PathVariable String stationName, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testQueryForTravel() throws Exception { Travel info = new Travel(); Mockito.when(basicService.queryForTravel(Mockito.any(Travel.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/basicservice/basic/travel").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
BasicController { @GetMapping(value = "/basic/{stationName}") public HttpEntity queryForStationId(@PathVariable String stationName, @RequestHeader HttpHeaders headers) { return ok(service.queryForStationId(stationName, headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @PostMapping(value = "/basic/travel") HttpEntity queryForTravel(@RequestBody Travel info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/basic/{stationName}") HttpEntity queryForStationId(@PathVariable String stationName, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testQueryForStationId() throws Exception { Mockito.when(basicService.queryForStationId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/basicservice/basic/stationName")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
RebookServiceImpl implements RebookService { public Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders) { Seat seatRequest = new Seat(); seatRequest.setTravelDate(date); seatRequest.setTrainNumber(tripId); seatRequest.setSeatType(seatType); seatRequest.setStartStation(startStationId); seatRequest.setDestStation(endStataionId); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, httpHeaders); ResponseEntity<Response<Ticket>> reTicket = restTemplate.exchange( "http: HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { }); return reTicket.getBody().getData(); } @Override Response rebook(RebookInfo info, HttpHeaders httpHeaders); @Override Response payDifference(RebookInfo info, HttpHeaders httpHeaders); Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders); }### Answer:
@Test public void testDipatchSeat() { long mills = System.currentTimeMillis(); Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); HttpEntity requestEntityTicket = new HttpEntity<>(seatRequest, headers); Response<Ticket> response = new Response<>(); ResponseEntity<Response<Ticket>> reTicket = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http: HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { })).thenReturn(reTicket); Ticket result = rebookServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); Assert.assertNull(result); } |
### Question:
InsidePaymentController { @PostMapping(value = "/inside_payment/account") public HttpEntity createAccount(@RequestBody AccountInfo info, @RequestHeader HttpHeaders headers) { return ok(service.createAccount(info, headers)); } @GetMapping(path = "/welcome") String home(); @PostMapping(value = "/inside_payment") HttpEntity pay(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/account") HttpEntity createAccount(@RequestBody AccountInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/{userId}/{money}") HttpEntity addMoney(@PathVariable String userId, @PathVariable
String money, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/payment") HttpEntity queryPayment(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/account") HttpEntity queryAccount(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/drawback/{userId}/{money}") HttpEntity drawBack(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/difference") HttpEntity payDifference(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/money") HttpEntity queryAddMoney(@RequestHeader HttpHeaders headers); @Autowired
public InsidePaymentService service; }### Answer:
@Test public void testCreateAccount() throws Exception { AccountInfo info = new AccountInfo(); Mockito.when(service.createAccount(Mockito.any(AccountInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/inside_pay_service/inside_payment/account").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
RebookController { @GetMapping(path = "/welcome") public String home() { return "Welcome to [ Rebook Service ] !"; } @GetMapping(path = "/welcome") String home(); @PostMapping(value = "/rebook/difference") HttpEntity payDifference(@RequestBody RebookInfo info,
@RequestHeader HttpHeaders headers); @PostMapping(value = "/rebook") HttpEntity rebook(@RequestBody RebookInfo info, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/rebookservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Rebook Service ] !")); } |
### Question:
RebookController { @PostMapping(value = "/rebook/difference") public HttpEntity payDifference(@RequestBody RebookInfo info, @RequestHeader HttpHeaders headers) { return ok(service.payDifference(info, headers)); } @GetMapping(path = "/welcome") String home(); @PostMapping(value = "/rebook/difference") HttpEntity payDifference(@RequestBody RebookInfo info,
@RequestHeader HttpHeaders headers); @PostMapping(value = "/rebook") HttpEntity rebook(@RequestBody RebookInfo info, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testPayDifference() throws Exception { RebookInfo info = new RebookInfo(); Mockito.when(service.payDifference(Mockito.any(RebookInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/rebookservice/rebook/difference").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
RebookController { @PostMapping(value = "/rebook") public HttpEntity rebook(@RequestBody RebookInfo info, @RequestHeader HttpHeaders headers) { RebookController.LOGGER.info("[Rebook Service] OrderId: {} Old Trip Id: {} New Trip Id: {} Date: {} Seat Type: {}", info.getOrderId(), info.getOldTripId(), info.getTripId(), info.getDate(), info.getSeatType()); return ok(service.rebook(info, headers)); } @GetMapping(path = "/welcome") String home(); @PostMapping(value = "/rebook/difference") HttpEntity payDifference(@RequestBody RebookInfo info,
@RequestHeader HttpHeaders headers); @PostMapping(value = "/rebook") HttpEntity rebook(@RequestBody RebookInfo info, @RequestHeader HttpHeaders headers); }### Answer:
@Test public void testRebook() throws Exception { RebookInfo info = new RebookInfo(); Mockito.when(service.rebook(Mockito.any(RebookInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/rebookservice/rebook").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
ConsignPriceServiceImpl implements ConsignPriceService { @Override public Response queryPriceInformation(HttpHeaders headers) { StringBuilder sb = new StringBuilder(); ConsignPrice price = repository.findByIndex(0); sb.append("The price of weight within "); sb.append(price.getInitialWeight()); sb.append(" is "); sb.append(price.getInitialPrice()); sb.append(". The price of extra weight within the region is "); sb.append(price.getWithinPrice()); sb.append(" and beyond the region is "); sb.append(price.getBeyondPrice()); sb.append("\n"); return new Response<>(1, success, sb.toString()); } @Override Response getPriceByWeightAndRegion(double weight, boolean isWithinRegion, HttpHeaders headers); @Override Response queryPriceInformation(HttpHeaders headers); @Override Response createAndModifyPrice(ConsignPrice config, HttpHeaders headers); @Override Response getPriceConfig(HttpHeaders headers); }### Answer:
@Test public void testQueryPriceInformation() { ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.queryPriceInformation(headers); String str = "The price of weight within 2.0 is 3.0. The price of extra weight within the region is 3.5 and beyond the region is 4.0\n"; Assert.assertEquals(new Response<>(1, "Success", str), result); } |
### Question:
ConsignPriceServiceImpl implements ConsignPriceService { @Override public Response getPriceConfig(HttpHeaders headers) { return new Response<>(1, success, repository.findByIndex(0)); } @Override Response getPriceByWeightAndRegion(double weight, boolean isWithinRegion, HttpHeaders headers); @Override Response queryPriceInformation(HttpHeaders headers); @Override Response createAndModifyPrice(ConsignPrice config, HttpHeaders headers); @Override Response getPriceConfig(HttpHeaders headers); }### Answer:
@Test public void testGetPriceConfig() { ConsignPrice config = new ConsignPrice(); Mockito.when(repository.findByIndex(0)).thenReturn(config); Response result = consignPriceServiceImpl.getPriceConfig(headers); Assert.assertEquals(new Response<>(1, "Success", config), result); } |
### Question:
InsidePaymentController { @GetMapping(value = "/inside_payment/{userId}/{money}") public HttpEntity addMoney(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers) { return ok(service.addMoney(userId, money, headers)); } @GetMapping(path = "/welcome") String home(); @PostMapping(value = "/inside_payment") HttpEntity pay(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/account") HttpEntity createAccount(@RequestBody AccountInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/{userId}/{money}") HttpEntity addMoney(@PathVariable String userId, @PathVariable
String money, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/payment") HttpEntity queryPayment(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/account") HttpEntity queryAccount(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/drawback/{userId}/{money}") HttpEntity drawBack(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/difference") HttpEntity payDifference(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/money") HttpEntity queryAddMoney(@RequestHeader HttpHeaders headers); @Autowired
public InsidePaymentService service; }### Answer:
@Test public void testAddMoney() throws Exception { Mockito.when(service.addMoney(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/inside_payment/user_id/money")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
ConsignPriceController { @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ ConsignPrice Service ] !"; } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion,
@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/price") HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/config") HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers); @PostMapping(value = "/consignprice") HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ ConsignPrice Service ] !")); } |
### Question:
ConsignPriceController { @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") public HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion, @RequestHeader HttpHeaders headers) { return ok(service.getPriceByWeightAndRegion(Double.parseDouble(weight), Boolean.parseBoolean(isWithinRegion), headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion,
@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/price") HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/config") HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers); @PostMapping(value = "/consignprice") HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testGetPriceByWeightAndRegion() throws Exception { Mockito.when(service.getPriceByWeightAndRegion(Mockito.anyDouble(), Mockito.anyBoolean(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/consignprice/1.0/true")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
ConsignPriceController { @GetMapping(value = "/consignprice/price") public HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers) { return ok(service.queryPriceInformation(headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion,
@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/price") HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/config") HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers); @PostMapping(value = "/consignprice") HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testGetPriceInfo() throws Exception { Mockito.when(service.queryPriceInformation(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/consignprice/price")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
ConsignPriceController { @GetMapping(value = "/consignprice/config") public HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers) { return ok(service.getPriceConfig(headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion,
@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/price") HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/config") HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers); @PostMapping(value = "/consignprice") HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testGetPriceConfig() throws Exception { Mockito.when(service.getPriceConfig(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/consignprice/config")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
ConsignPriceController { @PostMapping(value = "/consignprice") public HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig, @RequestHeader HttpHeaders headers) { return ok(service.createAndModifyPrice(priceConfig, headers)); } @GetMapping(path = "/welcome") String home(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion,
@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/price") HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers); @GetMapping(value = "/consignprice/config") HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers); @PostMapping(value = "/consignprice") HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig,
@RequestHeader HttpHeaders headers); }### Answer:
@Test public void testModifyPriceConfig() throws Exception { ConsignPrice priceConfig = new ConsignPrice(); Mockito.when(service.createAndModifyPrice(Mockito.any(ConsignPrice.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(priceConfig); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/consignpriceservice/consignprice").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
ContactsServiceImpl implements ContactsService { @Override public Response findContactsById(UUID id, HttpHeaders headers) { LOGGER.info("FIND CONTACTS BY ID: " + id); Contacts contacts = contactsRepository.findById(id); if (contacts != null) { return new Response<>(1, success, contacts); } else { return new Response<>(0, "No contacts according to contacts id", null); } } @Override Response findContactsById(UUID id, HttpHeaders headers); @Override Response findContactsByAccountId(UUID accountId, HttpHeaders headers); @Override Response createContacts(Contacts contacts, HttpHeaders headers); @Override Response create(Contacts addContacts, HttpHeaders headers); @Override Response delete(UUID contactsId, HttpHeaders headers); @Override Response modify(Contacts contacts, HttpHeaders headers); @Override Response getAllContacts(HttpHeaders headers); }### Answer:
@Test public void testFindContactsById1() { UUID id = UUID.randomUUID(); Contacts contacts = new Contacts(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(contacts); Response result = contactsServiceImpl.findContactsById(id, headers); Assert.assertEquals(new Response<>(1, "Success", contacts), result); }
@Test public void testFindContactsById2() { UUID id = UUID.randomUUID(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(null); Response result = contactsServiceImpl.findContactsById(id, headers); Assert.assertEquals(new Response<>(0, "No contacts according to contacts id", null), result); } |
### Question:
ContactsServiceImpl implements ContactsService { @Override public Response findContactsByAccountId(UUID accountId, HttpHeaders headers) { ArrayList<Contacts> arr = contactsRepository.findByAccountId(accountId); ContactsServiceImpl.LOGGER.info("[Contacts-Query-Service][Query-Contacts] Result Size: {}", arr.size()); return new Response<>(1, success, arr); } @Override Response findContactsById(UUID id, HttpHeaders headers); @Override Response findContactsByAccountId(UUID accountId, HttpHeaders headers); @Override Response createContacts(Contacts contacts, HttpHeaders headers); @Override Response create(Contacts addContacts, HttpHeaders headers); @Override Response delete(UUID contactsId, HttpHeaders headers); @Override Response modify(Contacts contacts, HttpHeaders headers); @Override Response getAllContacts(HttpHeaders headers); }### Answer:
@Test public void testFindContactsByAccountId() { UUID accountId = UUID.randomUUID(); ArrayList<Contacts> arr = new ArrayList<>(); Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(arr); Response result = contactsServiceImpl.findContactsByAccountId(accountId, headers); Assert.assertEquals(new Response<>(1, "Success", arr), result); } |
### Question:
ContactsServiceImpl implements ContactsService { @Override public Response createContacts(Contacts contacts, HttpHeaders headers) { Contacts contactsTemp = contactsRepository.findById(contacts.getId()); if (contactsTemp != null) { ContactsServiceImpl.LOGGER.info("[Contacts Service][Init Contacts] Already Exists Id: {}", contacts.getId()); return new Response<>(0, "Already Exists", contactsTemp); } else { contactsRepository.save(contacts); return new Response<>(1, "Create Success", null); } } @Override Response findContactsById(UUID id, HttpHeaders headers); @Override Response findContactsByAccountId(UUID accountId, HttpHeaders headers); @Override Response createContacts(Contacts contacts, HttpHeaders headers); @Override Response create(Contacts addContacts, HttpHeaders headers); @Override Response delete(UUID contactsId, HttpHeaders headers); @Override Response modify(Contacts contacts, HttpHeaders headers); @Override Response getAllContacts(HttpHeaders headers); }### Answer:
@Test public void testCreateContacts1() { Contacts contacts = new Contacts(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(contacts); Response result = contactsServiceImpl.createContacts(contacts, headers); Assert.assertEquals(new Response<>(0, "Already Exists", contacts), result); }
@Test public void testCreateContacts2() { Contacts contacts = new Contacts(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(null); Mockito.when(contactsRepository.save(Mockito.any(Contacts.class))).thenReturn(null); Response result = contactsServiceImpl.createContacts(contacts, headers); Assert.assertEquals(new Response<>(1, "Create Success", null), result); } |
### Question:
InsidePaymentController { @GetMapping(value = "/inside_payment/payment") public HttpEntity queryPayment(@RequestHeader HttpHeaders headers) { return ok(service.queryPayment(headers)); } @GetMapping(path = "/welcome") String home(); @PostMapping(value = "/inside_payment") HttpEntity pay(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/account") HttpEntity createAccount(@RequestBody AccountInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/{userId}/{money}") HttpEntity addMoney(@PathVariable String userId, @PathVariable
String money, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/payment") HttpEntity queryPayment(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/account") HttpEntity queryAccount(@RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/drawback/{userId}/{money}") HttpEntity drawBack(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers); @PostMapping(value = "/inside_payment/difference") HttpEntity payDifference(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers); @GetMapping(value = "/inside_payment/money") HttpEntity queryAddMoney(@RequestHeader HttpHeaders headers); @Autowired
public InsidePaymentService service; }### Answer:
@Test public void testQueryPayment() throws Exception { Mockito.when(service.queryPayment(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/inside_payment/payment")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } |
### Question:
ContactsServiceImpl implements ContactsService { @Override public Response delete(UUID contactsId, HttpHeaders headers) { contactsRepository.deleteById(contactsId); Contacts contacts = contactsRepository.findById(contactsId); if (contacts == null) { ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][DeleteContacts] Success."); return new Response<>(1, "Delete success", contactsId); } else { ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][DeleteContacts] Fail.Reason not clear."); return new Response<>(0, "Delete failed", contactsId); } } @Override Response findContactsById(UUID id, HttpHeaders headers); @Override Response findContactsByAccountId(UUID accountId, HttpHeaders headers); @Override Response createContacts(Contacts contacts, HttpHeaders headers); @Override Response create(Contacts addContacts, HttpHeaders headers); @Override Response delete(UUID contactsId, HttpHeaders headers); @Override Response modify(Contacts contacts, HttpHeaders headers); @Override Response getAllContacts(HttpHeaders headers); }### Answer:
@Test public void testDelete1() { UUID contactsId = UUID.randomUUID(); Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class)); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(null); Response result = contactsServiceImpl.delete(contactsId, headers); Assert.assertEquals(new Response<>(1, "Delete success", contactsId), result); }
@Test public void testDelete2() { UUID contactsId = UUID.randomUUID(); Contacts contacts = new Contacts(); Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class)); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(contacts); Response result = contactsServiceImpl.delete(contactsId, headers); Assert.assertEquals(new Response<>(0, "Delete failed", contactsId), result); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.