method2testcases
stringlengths 118
3.08k
|
---|
### Question:
AppManager { public Boolean save(App app) { if (appDao.save(app)){ return appDao.index(app); } return Boolean.FALSE; } Boolean delete(Long appId); Boolean save(App app); }### Answer:
@Test public void testSave(){ App app = new App(); app.setAppName("test_app"); app.setAppKey("123456"); app.setAppDesc("测试应用"); assertTrue(appManager.save(app)); assertNotNull(appDao.findByName(app.getAppName())); } |
### Question:
AppManager { public Boolean delete(Long appId){ App app = appDao.findById(appId); if (app == null){ return Boolean.TRUE; } if(appDao.unIndex(app)){ return appDao.delete(app.getId()); } return Boolean.FALSE; } Boolean delete(Long appId); Boolean save(App app); }### Answer:
@Test public void testDelete(){ assertTrue(appManager.delete(4L)); assertTrue(appManager.delete(404L)); } |
### Question:
JobManager { public Boolean save(Job job){ boolean isCreate = job.getId() == null; boolean success = jobDao.save(job); if (success){ if (isCreate){ if(jobDao.bindApp(job.getAppId(), job.getId())){ success = jobDao.indexJobClass(job.getAppId(), job.getId(), job.getClazz()); } else { success = false; } if (!success){ delete(job.getId()); } } } return success; } Boolean save(Job job); Boolean delete(Long jobId); }### Answer:
@Test public void testSave(){ Job job = new Job(); job.setAppId(1L); job.setClazz("me.hao0.antares.client.job.HelloJob"); job.setCron("0/30 * * * * ?"); job.setStatus(JobStatus.ENABLE.value()); job.setType(JobType.DEFAULT.value()); assertTrue(jobManager.save(job)); } |
### Question:
JobManager { public Boolean delete(Long jobId){ Job job = jobDao.findById(jobId); if (job == null){ return Boolean.TRUE; } if (jobDao.unbindApp(job.getAppId(), jobId)){ return jobDao.delete(jobId) && jobDao.unIndexJobClass(job.getAppId(), job.getClazz()); } return Boolean.FALSE; } Boolean save(Job job); Boolean delete(Long jobId); }### Answer:
@Test public void testDelete(){ } |
### Question:
CrudService { public T fetchById(UUID id) { T item = db.find(type, id); if (item == null) { throw new NotFoundException(id); } return item; } @Inject CrudService(Class<T> type, EbeanServer db); T fetchById(UUID id); List<T> fetchByFilter(ListFiltering filter); T create(T item); T update(UUID id, T item); void delete(UUID id); }### Answer:
@Test public void fetchShouldFindInDatabase() { UUID id = UUID.randomUUID(); TestItem item = new TestItem(); when(db.find(TestItem.class, id)).thenReturn(item); assertThat(service.fetchById(id)).isEqualTo(item); }
@Test(expected = NotFoundException.class) public void fetchShouldThrowWhenIdNotFound() { service.fetchById(UUID.randomUUID()); } |
### Question:
RabbitMQMessageQueue implements MessageQueue<T> { @Override public void publish(T message) { try { channel.basicPublish("", name, MessageProperties.PERSISTENT_TEXT_PLAIN, MAPPER.writeValueAsBytes(message)); publish.mark(); if (log.isTraceEnabled()) { log.trace("Published to '{}' with data '{}'.", name, MAPPER.writeValueAsString(message)); } } catch (IOException e) { throw new MessageQueueException("Unable to publish to queue.", e); } } RabbitMQMessageQueue(Channel channel, String name, Class<T> type, MetricRegistry metrics); @Override void publish(T message); @Override Closeable consume(Function<T, Void> processor); @Override T consumeNext(); }### Answer:
@Test public void shouldPublishPersistentMessageToQueue() throws IOException { RabbitMQMessageQueue<TestMsg> queue = new RabbitMQMessageQueue<>(channel, QUEUE_NAME, TestMsg.class, metrics); TestMsg message = new TestMsg("blah", 5); byte[] messageBytes = Jackson.newObjectMapper().writeValueAsBytes(message); queue.publish(message); verify(channel).basicPublish(Matchers.eq(""), Matchers.eq(QUEUE_NAME), Matchers.eq(MessageProperties.PERSISTENT_TEXT_PLAIN), Matchers.eq(messageBytes)); }
@Test public void shouldRecordPublishMetrics() { RabbitMQMessageQueue<TestMsg> queue = new RabbitMQMessageQueue<>(channel, QUEUE_NAME, TestMsg.class, metrics); queue.publish(new TestMsg("blah", 5)); assertThat(metrics.meter("queue.TestMsg.test.publish").getCount()).isEqualTo(1); } |
### Question:
RabbitMQMessageQueue implements MessageQueue<T> { @Override public Closeable consume(Function<T, Void> processor) { Consumer consumer = new FunctionConsumer<>(channel, processor, type, name, metrics); try { String tag = channel.basicConsume(name, false, consumer); log.info("Set up consumer '{}' for queue '{}'.", tag, name); return () -> channel.basicCancel(tag); } catch (IOException e) { throw new MessageQueueException("Unable to set up consumer.", e); } } RabbitMQMessageQueue(Channel channel, String name, Class<T> type, MetricRegistry metrics); @Override void publish(T message); @Override Closeable consume(Function<T, Void> processor); @Override T consumeNext(); }### Answer:
@Test public void shouldConsumeByAttachingConsumerToQueue() throws IOException { RabbitMQMessageQueue<TestMsg> queue = new RabbitMQMessageQueue<>(channel, QUEUE_NAME, TestMsg.class, metrics); queue.consume(msg -> null); verify(channel).basicConsume(Matchers.eq(QUEUE_NAME), Matchers.eq(false), Matchers.any(FunctionConsumer.class)); } |
### Question:
HashedValue { public boolean equalsPlaintext(String plaintext) { return BCrypt.checkpw(plaintext, hashedValue); } HashedValue(String plaintext); boolean equalsPlaintext(String plaintext); }### Answer:
@Test public void shouldEqualOriginalPlaintext() { HashedValue hashed = new HashedValue("test"); assertThat(hashed.equalsPlaintext("test")).isTrue(); }
@Test public void shouldNotEqualDifferentPlaintext() { HashedValue hashed = new HashedValue("test"); assertThat(hashed.equalsPlaintext("nottest")).isFalse(); } |
### Question:
EmailServiceFactory implements Factory<EmailService> { @Override public EmailService provide() { if (!config.getEmail().isEnabled() || config.getSendGrid() == null) { log.info("Email sending disabled, logging them to console instead."); return new LoggerEmailService(); } else { log.info("Email sending enabled with SendGrid username {}.", config.getSendGrid().getUsername()); return locator.getService(SendGridEmailService.class); } } @Inject EmailServiceFactory(HasSendGridConfiguration config, ServiceLocator locator); @Override EmailService provide(); @Override void dispose(EmailService instance); }### Answer:
@Test public void shouldCreateLoggerServiceWhenEmailsAreDisabled() { TestConfiguration config = new TestConfiguration(); config.getEmail().setEnabled(false); EmailService email = new EmailServiceFactory(config, null).provide(); assertThat(email).isInstanceOf(LoggerEmailService.class); } |
### Question:
QueueWorker implements Runnable { @Override public void run() { cancel = queue.consume(this::process); } QueueWorker(MessageQueue<T> queue); @Override void run(); void cancel(); }### Answer:
@Test public void shouldConsumeProcessingFunctionWhenRun() { @SuppressWarnings("unchecked") MessageQueue<String> queue = mock(MessageQueue.class); new TestWorker(queue).run(); verify(queue).consume(Matchers.any()); } |
### Question:
LintRegistry extends IssueRegistry { @Override public List<Issue> getIssues() { return ImmutableList.of(AndroidLogDetector.ISSUE, HardcodedColorsDetector.ISSUE, DirectMaterialPaletteColorUsageDetector.ISSUE, NonMaterialColorsDetector.ISSUE); } @Override List<Issue> getIssues(); }### Answer:
@Test public void number_of_issues_registered() { int size = lintRegistry.getIssues().size(); assertThat(size).isEqualTo(NUMBER_OF_EXISTING_DETECTORS); }
@Test public void issues_verification() { List<Issue> actual = lintRegistry.getIssues(); assertThat(actual).contains(AndroidLogDetector.ISSUE); assertThat(actual).contains(HardcodedColorsDetector.ISSUE); assertThat(actual).contains(DirectMaterialPaletteColorUsageDetector.ISSUE); assertThat(actual).contains(NonMaterialColorsDetector.ISSUE); } |
### Question:
SupportActivityUtils { @SuppressWarnings("WeakerAccess") public static void addSupportFragmentToActivity(@NonNull final FragmentManager fragmentManager, @NonNull final Fragment fragment, @NonNull final String tag) { checkNotNull(fragmentManager, "fragmentManager must not be null!"); checkNotNull(fragment, "fragment must not be null!"); checkNotNull(tag, "tag must not be null!"); checkArgument(!tag.isEmpty(), "tag string must not be empty!"); removeSupportFragment(fragmentManager, tag); final FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(fragment, tag); transaction.commitAllowingStateLoss(); } private SupportActivityUtils(); @SuppressWarnings("WeakerAccess") static void addSupportFragmentToActivity(@NonNull final FragmentManager fragmentManager,
@NonNull final Fragment fragment,
@NonNull final String tag); @NonNull static Fragment findOrCreateSupportFragment(@NonNull final FragmentManager fragmentManager, @NonNull final String tag); @SuppressWarnings("WeakerAccess") static void removeSupportFragment(@NonNull final FragmentManager fragmentManager,
@NonNull final String tag); }### Answer:
@Test public void addSupportFragmentToActivity_AddsNewFragment() { SupportActivityUtils.addSupportFragmentToActivity(mFragmentManager, mFragment, TEST_TAG); then(mFragmentTransaction).should().add(mFragment, TEST_TAG); }
@Test public void addSupportFragmentToActivity_WhenFragmentWithGivenTagExists_ThenRemovesDuplicate() { given(mFragmentManager.findFragmentByTag(TEST_TAG)).willReturn(mFragment); SupportActivityUtils.addSupportFragmentToActivity(mFragmentManager, mFragment, TEST_TAG); then(mFragmentTransaction).should().remove(mFragment); } |
### Question:
DiffRequestManagerHolder { void recycle() { for (DiffRequestManager manager : mDiffRequestManagers.values()) { manager.releaseResources(); } mDiffRequestManagers.clear(); } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }### Answer:
@Test public void recycle_ReleasesResourcesOfEachManager() { mDiffRequestManagerHolder.recycle(); then(mDiffRequestManager).should().releaseResources(); } |
### Question:
DiffRequestManagerHolder { void configurationChanged() { for (DiffRequestManager manager : mDiffRequestManagers.values()) { manager.swapAdapter(null); } } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }### Answer:
@Test public void configurationChanged_ClearsCurrentAdapters() { mDiffRequestManagerHolder.configurationChanged(); then(mDiffRequestManager).should().swapAdapter(null); } |
### Question:
DiffRequest { @Override public String toString() { return "DiffRequest{" + "mDiffCallback=" + mDiffCallback + ", mTag='" + mTag + '\'' + ", mNewData=" + mNewData + ", mDetectMoves=" + mDetectMoves + '}'; } @SuppressWarnings("WeakerAccess") DiffRequest(final boolean detectMoves, @NonNull final String tag, @Nullable final List<D> newData, @NonNull final DiffUtil.Callback diffCallback); @NonNull DiffUtil.Callback getDiffCallback(); @NonNull String getTag(); @SuppressWarnings("WeakerAccess") boolean isDetectingMoves(); @Nullable List<D> getNewData(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toString_IsCorrect() { assertThat(new DiffRequest<String>(true, Constants.DIFF_REQUEST_MANAGER_DEFAULT_TAG, null, mDataComparable).toString(), startsWith("DiffRequest")); } |
### Question:
DiffRequest { @NonNull public DiffUtil.Callback getDiffCallback() { return mDiffCallback; } @SuppressWarnings("WeakerAccess") DiffRequest(final boolean detectMoves, @NonNull final String tag, @Nullable final List<D> newData, @NonNull final DiffUtil.Callback diffCallback); @NonNull DiffUtil.Callback getDiffCallback(); @NonNull String getTag(); @SuppressWarnings("WeakerAccess") boolean isDetectingMoves(); @Nullable List<D> getNewData(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getDiffCallback_ReturnsCorrectCallback() { assertThat(mDiffRequest.getDiffCallback(), equalTo(mDataComparable)); } |
### Question:
DiffRequest { @NonNull public String getTag() { return mTag; } @SuppressWarnings("WeakerAccess") DiffRequest(final boolean detectMoves, @NonNull final String tag, @Nullable final List<D> newData, @NonNull final DiffUtil.Callback diffCallback); @NonNull DiffUtil.Callback getDiffCallback(); @NonNull String getTag(); @SuppressWarnings("WeakerAccess") boolean isDetectingMoves(); @Nullable List<D> getNewData(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getTag_ReturnsCorrectTag() { assertThat(mDiffRequest.getTag(), equalTo(Constants.DIFF_REQUEST_MANAGER_DEFAULT_TAG)); } |
### Question:
DiffRequest { @SuppressWarnings("WeakerAccess") public boolean isDetectingMoves() { return mDetectMoves; } @SuppressWarnings("WeakerAccess") DiffRequest(final boolean detectMoves, @NonNull final String tag, @Nullable final List<D> newData, @NonNull final DiffUtil.Callback diffCallback); @NonNull DiffUtil.Callback getDiffCallback(); @NonNull String getTag(); @SuppressWarnings("WeakerAccess") boolean isDetectingMoves(); @Nullable List<D> getNewData(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void isDetectingMoves_ReturnsCorrectBoolean() { assertThat(mDiffRequest.isDetectingMoves(), equalTo(true)); } |
### Question:
DiffRequest { @Nullable public List<D> getNewData() { return mNewData; } @SuppressWarnings("WeakerAccess") DiffRequest(final boolean detectMoves, @NonNull final String tag, @Nullable final List<D> newData, @NonNull final DiffUtil.Callback diffCallback); @NonNull DiffUtil.Callback getDiffCallback(); @NonNull String getTag(); @SuppressWarnings("WeakerAccess") boolean isDetectingMoves(); @Nullable List<D> getNewData(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getNewData_ReturnsCorrectNewData() { assertThat(mDiffRequest.getNewData(), equalTo(mNewData)); } |
### Question:
RxDiffResult { @Override public String toString() { return "RxDiffResult{" + "mTag='" + mTag + '\'' + ", mDiffResult=" + mDiffResult + '}'; } RxDiffResult(@NonNull final String tag, @NonNull final DiffUtil.DiffResult diffResult); @NonNull String getTag(); @NonNull DiffUtil.DiffResult getDiffResult(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toString_IsCorrect() { assertThat(new RxDiffResult(TEST_TAG, mDiffResult).toString(), startsWith("RxDiffResult")); } |
### Question:
RxDiffUtil { @NonNull public static DiffRequestManagerHolder bindTo(@NonNull final Activity activity) { checkNotNull(activity, "activity must not be null!"); return DiffRequestManagerHolderRetriever.retrieveFrom(activity); } private RxDiffUtil(); @NonNull static DiffRequestManagerHolder bindTo(@NonNull final Activity activity); }### Answer:
@Test public void bindTo_ReturnsNonNullHolder() { final DiffRequestManagerHolder holder = RxDiffUtil.bindTo(getActivity()); assertThat(holder, notNullValue()); } |
### Question:
DefaultDiffCallback extends DiffUtil.Callback { @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return mNewData.get(newItemPosition).equals(mOldData.get(oldItemPosition)); } DefaultDiffCallback(@NonNull final List<D> oldData,
@NonNull final List<D> newData); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override int getNewListSize(); @Override int getOldListSize(); @NonNull List<D> getOldData(); @NonNull List<D> getNewData(); }### Answer:
@Test public void areContentsTheSame_ComparesModelData() { boolean whenSameResult = callback.areContentsTheSame(0, 0); boolean whenDifferentResult = callback.areContentsTheSame(1, 1); assertThat(whenSameResult, is(true)); assertThat(whenDifferentResult, is(false)); } |
### Question:
DefaultDiffCallback extends DiffUtil.Callback { @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return mNewData.get(newItemPosition).getId().equals(mOldData.get(oldItemPosition).getId()); } DefaultDiffCallback(@NonNull final List<D> oldData,
@NonNull final List<D> newData); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override int getNewListSize(); @Override int getOldListSize(); @NonNull List<D> getOldData(); @NonNull List<D> getNewData(); }### Answer:
@Test public void areItemsTheSame_ComparesModelIds() { boolean whenDifferentResult = callback.areItemsTheSame(0, 0); boolean whenSameResult = callback.areItemsTheSame(1, 1); assertThat(whenSameResult, is(true)); assertThat(whenDifferentResult, is(false)); } |
### Question:
DefaultDiffCallback extends DiffUtil.Callback { @NonNull public List<D> getOldData() { return Collections.unmodifiableList(mOldData); } DefaultDiffCallback(@NonNull final List<D> oldData,
@NonNull final List<D> newData); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override int getNewListSize(); @Override int getOldListSize(); @NonNull List<D> getOldData(); @NonNull List<D> getNewData(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getOldData_ReturnsUnmodifiableList() { callback.getOldData().add(new TestModel("data", "tag")); } |
### Question:
DefaultDiffCallback extends DiffUtil.Callback { @NonNull public List<D> getNewData() { return Collections.unmodifiableList(mNewData); } DefaultDiffCallback(@NonNull final List<D> oldData,
@NonNull final List<D> newData); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override int getNewListSize(); @Override int getOldListSize(); @NonNull List<D> getOldData(); @NonNull List<D> getNewData(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getNewData_ReturnsUnmodifiableList() { callback.getNewData().add(new TestModel("data", "tag")); } |
### Question:
SupportActivityUtils { @NonNull public static Fragment findOrCreateSupportFragment(@NonNull final FragmentManager fragmentManager, @NonNull final String tag) { checkNotNull(fragmentManager, "fragmentManager must not be null!"); checkNotNull(tag, "tag must not be null!"); checkArgument(!tag.isEmpty(), "tag string must not be empty!"); Fragment fragment = fragmentManager.findFragmentByTag(tag); if (fragment == null) { fragment = SupportDiffRequestManagerHolderFragment.newInstance(DiffRequestManagerHolder.create()); addSupportFragmentToActivity(fragmentManager, fragment, tag); } return fragment; } private SupportActivityUtils(); @SuppressWarnings("WeakerAccess") static void addSupportFragmentToActivity(@NonNull final FragmentManager fragmentManager,
@NonNull final Fragment fragment,
@NonNull final String tag); @NonNull static Fragment findOrCreateSupportFragment(@NonNull final FragmentManager fragmentManager, @NonNull final String tag); @SuppressWarnings("WeakerAccess") static void removeSupportFragment(@NonNull final FragmentManager fragmentManager,
@NonNull final String tag); }### Answer:
@Test public void findOrCreateSupportFragment_WhenFragmentFound_ReturnsIt() { given(mFragmentManager.findFragmentByTag(TEST_TAG)).willReturn(mFragment); final Fragment retrievedFragment = SupportActivityUtils.findOrCreateSupportFragment(mFragmentManager, TEST_TAG); assertThat(retrievedFragment, notNullValue()); assertThat(retrievedFragment, is(mFragment)); }
@Test public void findOrCreateSupportFragment_WhenFragmentNotFound_CreatesNewFragment() { final Fragment retrievedFragment = SupportActivityUtils.findOrCreateSupportFragment(mFragmentManager, TEST_TAG); assertThat(retrievedFragment, notNullValue()); assertThat(retrievedFragment, instanceOf(SupportDiffRequestManagerHolderFragment.class)); } |
### Question:
DiffRequestBuilder { @NonNull public static <T> DiffRequestBuilder<T> create(@NonNull final Manager<T> diffRequestManager, @NonNull final DiffUtil.Callback callback) { return new DiffRequestBuilder<>(diffRequestManager, callback); } DiffRequestBuilder(@NonNull final Manager<D> diffRequestManager,
@NonNull final DiffUtil.Callback callback); @NonNull static DiffRequestBuilder<T> create(@NonNull final Manager<T> diffRequestManager,
@NonNull final DiffUtil.Callback callback); @NonNull DiffRequestBuilder<D> detectMoves(final boolean detectMoves); @NonNull DiffRequestBuilder<D> updateAdapterWithNewData(@NonNull final List<D> newData); void calculate(); boolean isDetectingMoves(); }### Answer:
@Test public void create_ReturnsNonNullBuilder() { final DiffRequestBuilder<TestModel> builder = DiffRequestBuilder.create(mDiffRequestManager, mCallback); assertThat(builder, notNullValue()); } |
### Question:
DiffRequestBuilder { public void calculate() { final DiffRequest<D> diffRequest = new DiffRequest<>(mDetectMoves, mTag, mNewData, mCallback); mDiffRequestManager.execute(diffRequest); } DiffRequestBuilder(@NonNull final Manager<D> diffRequestManager,
@NonNull final DiffUtil.Callback callback); @NonNull static DiffRequestBuilder<T> create(@NonNull final Manager<T> diffRequestManager,
@NonNull final DiffUtil.Callback callback); @NonNull DiffRequestBuilder<D> detectMoves(final boolean detectMoves); @NonNull DiffRequestBuilder<D> updateAdapterWithNewData(@NonNull final List<D> newData); void calculate(); boolean isDetectingMoves(); }### Answer:
@Test public void calculate_CreatesDiffRequest() { mBuilder.calculate(); then(mDiffRequestManager).should().execute(any(DiffRequest.class)); } |
### Question:
DiffRequestManagerHolder { @NonNull public static DiffRequestManagerHolder create() { return new DiffRequestManagerHolder(new HashMap<String, DiffRequestManager>()); } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }### Answer:
@Test public void create_ReturnsNonNullHolder() { final DiffRequestManagerHolder holder = DiffRequestManagerHolder.create(); assertThat(holder, notNullValue()); } |
### Question:
DiffRequestManagerHolder { @NonNull public DiffRequestManager getManager(@NonNull final String tag) { checkNotNull(tag, "tag must not be null!"); checkArgument(!tag.isEmpty(), "tag string must not be empty!"); final DiffRequestManager diffRequestManager = mDiffRequestManagers.get(tag); if (diffRequestManager == null) { throw new IllegalStateException("Failed to retrieve the manager matching the given tag. Probably you forgot to bind it to an activity."); } return diffRequestManager; } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }### Answer:
@Test public void getManager_ReturnsNonNullManager() { final DiffRequestManager diffRequestManager = mDiffRequestManagerHolder.getManager(TEST_TAG); assertThat(diffRequestManager, notNullValue()); } |
### Question:
DiffRequestManagerHolder { void addManager(@NonNull final DiffRequestManager manager, @NonNull final String tag) { checkNotNull(manager, "manager must not be null!"); checkNotNull(tag, "tag must not be null!"); checkArgument(!tag.isEmpty(), "tag string must not be empty!"); mDiffRequestManagers.put(tag, manager); } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }### Answer:
@Test public void addManager_AddsManagerToMap() { mDiffRequestManagerHolder.addManager(mDiffRequestManager, "TEST_TAG2"); assertThat(mDiffRequestManagers.size(), equalTo(2)); } |
### Question:
DiffRequestManagerHolder { @NonNull public <D, A extends RecyclerView.Adapter & Swappable<D>> DiffRequestManager<D, A> with(@NonNull final A adapter) { return with(adapter, Constants.DIFF_REQUEST_MANAGER_DEFAULT_TAG); } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }### Answer:
@Test public void with_ForwardsCallWithDefaultTag() { final DiffRequestManagerHolder spyDiffRequestManagerHolder = spy(mDiffRequestManagerHolder); spyDiffRequestManagerHolder.with(mTestAdapter); then(spyDiffRequestManagerHolder).should().with(mTestAdapter, Constants.DIFF_REQUEST_MANAGER_DEFAULT_TAG); } |
### Question:
HtmlTable extends AbstractHtmlTag { @Override public StringBuilder toHtml() { StringBuilder html = new StringBuilder(); html.append(getHtmlOpeningTag()); html.append(getHtmlHeader()); html.append(getHtmlBody()); html.append(getHtmlFooter()); html.append(getHtmlClosingTag()); return html; } HtmlTable(String id, HttpServletRequest request, HttpServletResponse response); HtmlTable(String id, HttpServletRequest request, HttpServletResponse response, String groupName); HtmlTable(String id, HttpServletRequest request, HttpServletResponse response, String groupName,
Map<String, String> dynamicAttributes); @Override StringBuilder toHtml(); HtmlCaption getCaption(); void setCaption(HtmlCaption caption); List<HtmlRow> getHeadRows(); List<HtmlRow> getBodyRows(); HtmlRow addHeaderRow(); HtmlRow addRow(); HtmlRow addFooterRow(); HtmlRow addRow(String rowId); HtmlTable addRows(HtmlRow... rows); HtmlRow getLastFooterRow(); HtmlRow getFirstHeaderRow(); HtmlRow getLastHeaderRow(); HtmlRow getLastBodyRow(); void addCssStyle(String cssStyle); void addCssClass(String cssClass); TableConfiguration getTableConfiguration(); void setTableConfiguration(TableConfiguration tableConfiguration); String getOriginalId(); void setOriginalId(String originalId); }### Answer:
@Test public void should_generate_table_with_an_unallowed_character_in_the_id() { table = new HtmlTable("table-id", request, response); assertThat(table.toHtml().toString()).isEqualTo("<table id=\"tableid\"><thead></thead></table>"); assertThat(table.getId()).isEqualTo("tableid"); }
@Test public void should_generate_table_with_id() { table = new HtmlTable("tableId", request, response); assertThat(table.toHtml().toString()).isEqualTo("<table id=\"tableId\"><thead></thead></table>"); } |
### Question:
HtmlColumn extends HtmlTagWithContent { public void addCssCellClass(String cssCellClass) { if (this.cssCellClass == null) { this.cssCellClass = new StringBuilder(); } else { this.cssCellClass.append(CLASS_SEPARATOR); } this.cssCellClass.append(cssCellClass); } HtmlColumn(); HtmlColumn(String displayFormat); HtmlColumn(Boolean isHeader); HtmlColumn(Boolean isHeader, String content); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes, String displayTypes); Boolean isHeaderColumn(); ColumnConfiguration getColumnConfiguration(); void setColumnConfiguration(ColumnConfiguration columnConfiguration); void addCssClass(String cssClass); void addCssCellClass(String cssCellClass); void addCssCellStyle(String cssCellStyle); Set<String> getEnabledDisplayTypes(); void setEnabledDisplayTypes(Set<String> enabledDisplayTypes); StringBuilder getCssCellStyle(); StringBuilder getCssCellClass(); }### Answer:
@Test public void should_generate_cell_tag_with_one_class() { createHtmlCellTag(); column.addCssCellClass("aClass"); assertThat(column.toHtml().toString()).isEqualTo("<" + column.getTag() + " class=\"aClass\"></" + column.getTag() + ">"); }
@Test public void should_generate_cell_tag_with_several_classes() { createHtmlCellTag(); column.addCssCellClass("oneClass"); column.addCssCellClass("twoClass"); assertThat(column.toHtml().toString()).isEqualTo("<" + column.getTag() + " class=\"oneClass twoClass\"></" + column.getTag() + ">"); } |
### Question:
HtmlColumn extends HtmlTagWithContent { public void addCssCellStyle(String cssCellStyle) { if (this.cssCellStyle == null) { this.cssCellStyle = new StringBuilder(); } else { this.cssCellStyle.append(STYLE_SEPARATOR); } this.cssCellStyle.append(cssCellStyle); } HtmlColumn(); HtmlColumn(String displayFormat); HtmlColumn(Boolean isHeader); HtmlColumn(Boolean isHeader, String content); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes, String displayTypes); Boolean isHeaderColumn(); ColumnConfiguration getColumnConfiguration(); void setColumnConfiguration(ColumnConfiguration columnConfiguration); void addCssClass(String cssClass); void addCssCellClass(String cssCellClass); void addCssCellStyle(String cssCellStyle); Set<String> getEnabledDisplayTypes(); void setEnabledDisplayTypes(Set<String> enabledDisplayTypes); StringBuilder getCssCellStyle(); StringBuilder getCssCellClass(); }### Answer:
@Test public void should_generate_cell_tag_with_one_style() { createHtmlCellTag(); column.addCssCellStyle("border:1px"); assertThat(column.toHtml().toString()).isEqualTo("<" + column.getTag() + " style=\"border:1px\"></" + column.getTag() + ">"); }
@Test public void should_generate_cell_tag_with_several_styles() { createHtmlCellTag(); column.addCssCellStyle("border:1px"); column.addCssCellStyle("align:center"); assertThat(column.toHtml().toString()).isEqualTo("<" + column.getTag() + " style=\"border:1px;align:center\"></" + column.getTag() + ">"); } |
### Question:
JstlLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { Object locale = Config.get(request, Config.FMT_LOCALE); if (locale == null) { HttpSession session = request.getSession(false); if (session != null) { locale = Config.get(session, Config.FMT_LOCALE); } } return (locale instanceof Locale ? (Locale) locale : null); } @Override Locale resolveLocale(HttpServletRequest request); }### Answer:
@Test public void should_resolve_locale_from_request_first(){ JstlLocaleResolver localeResolver = new JstlLocaleResolver(); Locale locale = localeResolver.resolveLocale(request); assertThat(locale).isEqualTo(en); }
@Test public void should_then_resolve_locale_from_session(){ Config.set(request, Config.FMT_LOCALE, null); JstlLocaleResolver localeResolver = new JstlLocaleResolver(); Locale locale = localeResolver.resolveLocale(request); assertThat(locale).isEqualTo(fr); } |
### Question:
HtmlRow extends AbstractHtmlTag { public List<HtmlColumn> getHeaderColumns() { List<HtmlColumn> retval = new ArrayList<HtmlColumn>(); for (HtmlColumn column : columns) { if (column.isHeaderColumn()) { retval.add(column); } } return retval; } HtmlRow(); HtmlRow(String id); @Override StringBuilder toHtml(); List<HtmlColumn> getColumns(String... enabledFormats); List<HtmlColumn> getColumns(); void setColumns(List<HtmlColumn> columns); HtmlColumn addHeaderColumn(HtmlColumn headerColumn); HtmlColumn addHeaderColumn(String columnContent); HtmlColumn addColumn(HtmlColumn column); HtmlColumn addColumn(String columnContent); HtmlColumn addColumn(String columnContent, String displayFormat); HtmlRow addHeaderColumns(String... columns); List<HtmlColumn> getHeaderColumns(); HtmlRow addColumns(String... columns); HtmlColumn getLastColumn(); @Override String toString(); }### Answer:
@Test public void should_get_header_columns() { populateColumns(); assertThat(row.getHeaderColumns()).containsExactly(headerColumn); } |
### Question:
HtmlRow extends AbstractHtmlTag { public HtmlColumn getLastColumn() { return ((LinkedList<HtmlColumn>) this.columns).getLast(); } HtmlRow(); HtmlRow(String id); @Override StringBuilder toHtml(); List<HtmlColumn> getColumns(String... enabledFormats); List<HtmlColumn> getColumns(); void setColumns(List<HtmlColumn> columns); HtmlColumn addHeaderColumn(HtmlColumn headerColumn); HtmlColumn addHeaderColumn(String columnContent); HtmlColumn addColumn(HtmlColumn column); HtmlColumn addColumn(String columnContent); HtmlColumn addColumn(String columnContent, String displayFormat); HtmlRow addHeaderColumns(String... columns); List<HtmlColumn> getHeaderColumns(); HtmlRow addColumns(String... columns); HtmlColumn getLastColumn(); @Override String toString(); }### Answer:
@Test public void should_get_last_column() { populateColumns(); assertThat(row.getLastColumn()).isEqualTo(column2); } |
### Question:
HtmlHyperlink extends HtmlTagWithContent { public void setHref(String href) { this.href = href; } HtmlHyperlink(); HtmlHyperlink(String href, String label); String getHref(); void setHref(String href); String getOnclick(); void setOnclick(String onclick); }### Answer:
@Test public void should_generate_full_ops_href_tag() { hyperlink.setId("fullId"); hyperlink.addCssClass("classy"); hyperlink.addCssStyle("styly"); hyperlink.setHref("fullHref"); hyperlink.addContent("valued"); assertThat(hyperlink.toHtml().toString()).isEqualTo("<a id=\"fullId\" class=\"classy\" style=\"styly\" href=\"fullHref\">valued</a>"); } |
### Question:
HtmlCaption extends HtmlTagWithContent { public void setTitle(String title) { this.title = title; } HtmlCaption(); String getTitle(); void setTitle(String title); }### Answer:
@Test public void should_generate_caption_tag_with_title(){ caption.setTitle("dummy title"); assertThat(caption.toHtml().toString()).isEqualTo("<caption title=\"dummy title\"></caption>"); }
@Test public void should_generate_full_ops_caption_tag(){ caption.setId("fullId"); caption.addCssClass("classy"); caption.addCssStyle("styly"); caption.setTitle("titly"); caption.addContent("valued"); assertThat(caption.toHtml().toString()).isEqualTo("<caption id=\"fullId\" class=\"classy\" style=\"styly\" title=\"titly\">valued</caption>"); } |
### Question:
HtmlColumn extends HtmlTagWithContent { public Set<String> getEnabledDisplayTypes() { return enabledDisplayTypes; } HtmlColumn(); HtmlColumn(String displayFormat); HtmlColumn(Boolean isHeader); HtmlColumn(Boolean isHeader, String content); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes, String displayTypes); Boolean isHeaderColumn(); ColumnConfiguration getColumnConfiguration(); void setColumnConfiguration(ColumnConfiguration columnConfiguration); void addCssClass(String cssClass); void addCssCellClass(String cssCellClass); void addCssCellStyle(String cssCellStyle); Set<String> getEnabledDisplayTypes(); void setEnabledDisplayTypes(Set<String> enabledDisplayTypes); StringBuilder getCssCellStyle(); StringBuilder getCssCellClass(); }### Answer:
@Test public void should_contain_all_display_types() { assertThat(column.getEnabledDisplayTypes()).contains(ReservedFormat.ALL); } |
### Question:
HtmlColumn extends HtmlTagWithContent { public Boolean isHeaderColumn() { return isHeaderColumn; } HtmlColumn(); HtmlColumn(String displayFormat); HtmlColumn(Boolean isHeader); HtmlColumn(Boolean isHeader, String content); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes); HtmlColumn(Boolean isHeader, String content, Map<String, String> dynamicAttributes, String displayTypes); Boolean isHeaderColumn(); ColumnConfiguration getColumnConfiguration(); void setColumnConfiguration(ColumnConfiguration columnConfiguration); void addCssClass(String cssClass); void addCssCellClass(String cssCellClass); void addCssCellStyle(String cssCellStyle); Set<String> getEnabledDisplayTypes(); void setEnabledDisplayTypes(Set<String> enabledDisplayTypes); StringBuilder getCssCellStyle(); StringBuilder getCssCellClass(); }### Answer:
@Test public void should_create_header_column_with_content() { column = new HtmlColumn(true, "content"); assertThat(column.isHeaderColumn()).isTrue(); assertThat(column.toHtml().toString()).isEqualTo("<" + column.getTag() + ">content</" + column.getTag() + ">"); }
@Test public void should_create_column_with_content() { column = new HtmlColumn(false, "content"); assertThat(column.isHeaderColumn()).isFalse(); assertThat(column.toHtml().toString()).isEqualTo("<" + column.getTag() + ">content</" + column.getTag() + ">"); } |
### Question:
BooleanConverters implements ConverterLoader { @Override public void loadConverters() { Converters.loadContainedConverters(BooleanConverters.class); } @Override void loadConverters(); }### Answer:
@Test public void testBooleanConverters() throws Exception { ConverterLoader loader = new BooleanConverters(); loader.loadConverters(); assertFromBoolean("BooleanToInteger", new BooleanConverters.BooleanToInteger(), 1, 0); assertFromBoolean("BooleanToString", new BooleanConverters.BooleanToString(), "true", "false"); assertToBoolean("IntegerToBoolean", new BooleanConverters.IntegerToBoolean(), 1, 0); assertToBoolean("StringToBoolean", new BooleanConverters.StringToBoolean(), "true", "false"); assertToCollection("BooleanToCollection", Boolean.TRUE); } |
### Question:
UtilGenerics { public static <E, C extends Collection<E>> C checkCollection(Object object, Class<E> type) { if (object != null) { if (!(Collection.class.isInstance(object))) { throw new ClassCastException("Not a " + Collection.class.getName()); } int i = 0; for (Object value: (Collection<?>) object) { if (value != null && !type.isInstance(value)) { throw new IllegalArgumentException("Value(" + i + "), with value(" + value + ") is not a " + type.getName()); } i++; } } return cast(object); } private UtilGenerics(); @SuppressWarnings("unchecked") static V cast(Object object); static C checkCollection(Object object, Class<E> type); static Map<K, V> checkMap(Object object, Class<K> keyType, Class<V> valueType); }### Answer:
@Test public void basicCheckCollection() { UtilGenerics.<String, Collection<String>>checkCollection(Arrays.asList("foo", "bar", "baz"), String.class); }
@Test(expected = ClassCastException.class) public void incompatibleCollectionCheckCollection() { UtilGenerics.<String, Collection<String>>checkCollection("not a collection", String.class); }
@Test(expected = IllegalArgumentException.class) public void heterogenousCheckCollection() { UtilGenerics.<String, Collection<String>>checkCollection(Arrays.asList("foo", 0), String.class); }
@Test public void nullCheckCollection() { assertNull(UtilGenerics.<String, Collection<String>>checkCollection(null, String.class)); } |
### Question:
MapContext implements Map<K, V>, LocalizedMap<V> { @Override public Collection<V> values() { return entryStream() .map(Map.Entry::getValue) .collect(collectingAndThen(toList(), Collections::unmodifiableCollection)); } Deque<Map<K, V>> getContexts(); void push(); void push(Map<K, V> existingMap); void addToBottom(Map<K, V> existingMap); Map<K, V> pop(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V get(String name, Locale locale); @Override V put(K key, V value); @Override V remove(Object key); @Override void putAll(Map<? extends K, ? extends V> arg0); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Map.Entry<K, V>> entrySet(); @Override String toString(); }### Answer:
@Test public void controllerConfigLikeContext() { Map<String, String> propsA = UtilMisc.toMap(LinkedHashMap::new, "aa", "1", "ab", "1"); Map<String, String> propsB = UtilMisc.toMap(LinkedHashMap::new, "ba", "3", "bb", "8", "bc", "1", "bd", "14"); PNode pn = new PNode(propsA, new PNode(propsB, new PNode(), new PNode()), new PNode(new PNode()), new PNode()); MapContext<String, String> mc = pn.allProps(); assertThat("insertion order of LinkedHashMap is preserved by the 'values' method", mc.values(), contains("1", "1", "3", "8", "1", "14")); } |
### Question:
Digraph { public List<T> sort() throws IllegalStateException { Set<T> permanents = new HashSet<>(); Set<T> temporaries = new HashSet<>(); List<T> result = new ArrayList<>(); for (T node : nodes) { if (!permanents.contains(node)) { visit(result, node, permanents, temporaries); } } return result; } Digraph(Map<T, Collection<T>> spec); List<T> sort(); }### Answer:
@Test(expected = IllegalStateException.class) public void testWithCycle() { Map<String, Collection<String>> g = UtilMisc.toMap( "a", asList("b"), "b", asList("c"), "c", asList("a")); Digraph<String> dg = new Digraph<>(g); dg.sort(); } |
### Question:
UtilHtml { public static List<String> hasUnclosedTag(String content) { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader eventReader = null; List<String> errorList = new ArrayList<>(); try { eventReader = inputFactory.createXMLEventReader( new ByteArrayInputStream(("<template>" + content + "</template>").getBytes(StandardCharsets.UTF_8)), "utf-8"); Stack<StartElement> stack = new Stack<StartElement>(); while (eventReader.hasNext()) { try { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); stack.push(startElement); } if (event.isEndElement()) { EndElement endElement = event.asEndElement(); stack.pop(); } } catch (XMLStreamException e) { if (!stack.isEmpty()) { StartElement startElement = stack.pop(); String elementName = startElement.getName().getLocalPart(); if (Arrays.stream(TAG_SHOULD_CLOSE_LIST).anyMatch(elementName::equals)) { errorList.add(e.getMessage()); } } else { errorList.add(e.getMessage()); } break; } } } catch (XMLStreamException e) { errorList.add(e.getMessage()); } finally { if (eventReader != null) { try { eventReader.close(); } catch (XMLStreamException e) { Debug.logError(e, MODULE); } } } return errorList; } private UtilHtml(); static List<ParseError> validateHtmlFragmentWithJSoup(String content); static List<String> hasUnclosedTag(String content); static List<String> getVisualThemeFolderNamesToExempt(); static void logHtmlWarning(String content, String location, String error, String module); }### Answer:
@Test public void parseHtmlFragmentUnclosedDiv() { List<String> errorList = UtilHtml.hasUnclosedTag("<div><div></div>"); assertEquals(true, errorList.get(0).contains("Unexpected close tag")); }
@Test public void parseHtmlFragmentMultiRoot() { List<String> errorList = UtilHtml.hasUnclosedTag("<div></div><div></div>"); assertEquals(0, errorList.size()); } |
### Question:
ComponentContainer implements Container { @Override public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException { init(name, Start.getInstance().getConfig().getOfbizHome()); } @Override void init(List<StartupCommand> ofbizCommands, String name, String configFile); @Override boolean start(); @Override void stop(); @Override String getName(); }### Answer:
@Test public void testCheckDependencyForComponent() throws ContainerException { ComponentContainer containerObj = new ComponentContainer(); containerObj.init("component-container", ofbizHome); List<String> loadedComponents = ComponentConfig.components() .map(ComponentConfig::getGlobalName) .collect(Collectors.toList()); assertEquals(Arrays.asList("order", "accounting"), loadedComponents); } |
### Question:
WebAppCache { public Optional<WebappInfo> getWebappInfo(String serverName, String webAppName) { return getAppBarWebInfos(serverName).stream() .filter(app -> app.getMountPoint().replaceAll("[/*]", "").equals(webAppName)) .findFirst(); } WebAppCache(Supplier<Collection<ComponentConfig>> supplier); List<WebappInfo> getAppBarWebInfos(String serverName); List<WebappInfo> getAppBarWebInfos(String serverName, String menuName); Optional<WebappInfo> getWebappInfo(String serverName, String webAppName); static WebAppCache getShared(); }### Answer:
@Test public void getWebappInfoBasic() { WebappInfo wInfo0 = new WebappInfo.Builder() .server("foo").position("7").mountPoint("/bar/*").create(); wInfos.add(wInfo0); WebappInfo wInfo1 = new WebappInfo.Builder() .server("foo").position("14").mountPoint("/bar/baz/*").create(); wInfos.add(wInfo1); assertThat(wac.getWebappInfo("foo", "bar").get(), is(wInfo0)); assertThat(wac.getWebappInfo("foo", "barbaz").get(), is(wInfo1)); assertFalse(wac.getWebappInfo("foo", "bazbaz").isPresent()); } |
### Question:
TwitterCrawler extends Crawler<TweetBundle> { @Override public void crawl() { if (hashTags == null) { loadHashTags(); } if (twitter == null) { configureTwitterAuthentication(); } List<Post> positivePosts = new ArrayList<>(); List<TweetBundle> tweetBundles = getRaw(); for (TweetBundle bundle : tweetBundles) { positivePosts.addAll(rawToPosts(bundle)); } logger.info("Filtered out " + (LOAD_TWEETS_PER_HASTAG * hashTags.length - positivePosts.size()) + " out of " + LOAD_TWEETS_PER_HASTAG * hashTags.length + " tweets"); if (positivePosts.size() >= MAX_TWEETS) { List<Post> postsToSave = positivePosts.subList(0, MAX_TWEETS); logger.info("Saving " + MAX_TWEETS + " tweets to the database"); savePosts(postsToSave); } else { logger.info("Saving " + positivePosts.size() + " tweets to the database"); savePosts(positivePosts); } } TwitterCrawler(); @Override void crawl(); List<Post> rawToPosts(TweetBundle tweets); }### Answer:
@Test public void crawl() throws Exception { setHashTags(); twitterCrawler.crawl(); } |
### Question:
TwitterCrawler extends Crawler<TweetBundle> { @Override List<TweetBundle> getRaw() { logger.info("Started getting tweets from twitter"); List<TweetBundle> tweetBundles = new ArrayList(); for (int i = 0; i < hashTags.length; i++) { hashTag = hashTags[i]; Query query = new Query(hashTag); query.count(LOAD_TWEETS_PER_HASTAG); try { QueryResult result = twitter.search(query); TweetBundle rawTweets = new TweetBundle(hashTag); List<Status> rawData = result.getTweets(); rawTweets.addTweets(rawData); tweetBundles.add(rawTweets); logger.info("Received total of " + rawTweets.getTweets() .size() + " tweets from twitter with " + hashTag); } catch (TwitterException e) { logger.error("TwitterException: " + e.getErrorMessage()); } } return tweetBundles; } TwitterCrawler(); @Override void crawl(); List<Post> rawToPosts(TweetBundle tweets); }### Answer:
@Test public void getRaw() throws Exception { twitterCrawler.configureTwitterAuthentication(); setHashTags(); List<TweetBundle> rawData = twitterCrawler.getRaw(); assertTrue(rawData.size() > 0); assertTrue(!rawData.get(0).getHashTag().equals("")); assertTrue(rawData.get(0).getTweets().size() != 0); } |
### Question:
TwitterCrawler extends Crawler<TweetBundle> { public List<Post> rawToPosts(TweetBundle tweets) { Date d = new Date(System.currentTimeMillis() - 3600 * 1000); return tweets.getTweets().stream() .filter(status -> !status.isPossiblySensitive() && status.getText().matches("\\A\\p{ASCII}*\\z") && status.getCreatedAt().after(d) && !status.getText().contains("RT") && status.getRetweetCount() > 0) .map(this::convertStatusToPost) .collect(Collectors.toList()); } TwitterCrawler(); @Override void crawl(); List<Post> rawToPosts(TweetBundle tweets); }### Answer:
@Test public void rawToPosts() throws Exception { Status mockStatus = mock(Status.class); when(mockStatus.getText()).thenReturn("mocktext"); User user = mock(User.class); when(user.getScreenName()).thenReturn("testuser"); when(mockStatus.getUser()).thenReturn(user); when(mockStatus.getCreatedAt()).thenReturn(new Date()); when(mockStatus.getId()).thenReturn((long) 5412); when(mockStatus.getRetweetCount()).thenReturn(100); HashtagEntity hashtag = mock(HashtagEntity.class); when(hashtag.getText()).thenReturn("hastak"); HashtagEntity[] entities = new HashtagEntity[]{hashtag}; when(mockStatus.getHashtagEntities()).thenReturn(entities); ArrayList<Status> rawTweets = new ArrayList<>(); rawTweets.add(mockStatus); TweetBundle tweetBundle = new TweetBundle("hastak"); tweetBundle.addTweets(rawTweets); List<Post> posts = twitterCrawler.rawToPosts(tweetBundle); assertTrue(posts.size() > 0); } |
### Question:
PostController { @ApiOperation("Get a post by its UUID") @RequestMapping(value = "/uuid/{uuid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Post getPostByUuid(@PathVariable("uuid") String uuid) { return postRepository.findOne(uuid); } @Autowired PostController(PostRepository postRepository); @ApiOperation("Get all posts in a paginated format") @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) Page<Post> getAllByPage(Pageable pageable, @RequestParam(value = "whitelist", required = false)
String[] sourcesWhitelist, @RequestParam(required = false, defaultValue = "") String query); @ApiOperation("Get a post by its UUID") @RequestMapping(value = "/uuid/{uuid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) Post getPostByUuid(@PathVariable("uuid") String uuid); @ApiOperation("Get posts after a given date") @RequestMapping(value = "/afterdate/{date}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) Iterable<Post> getPostAfterDate(
@PathVariable("date") long date,
@RequestParam(required = false, defaultValue = "true", value = "ordered") boolean ordered,
@PathVariable(required = false) String[] sourcesWhitelist); @ApiOperation("flag a post by its UUID") @RequestMapping(value = "/{uuid}/flag", method = RequestMethod.POST) void flagPost(@PathVariable("uuid") String uuid,
@RequestBody FlagRequest body); }### Answer:
@Test public void getPostByUuid() throws Exception { this.mockMvc.perform(get("/post/uuid/{uuid}", posts.get(1).getUuid())) .andExpect(status().isOk()) .andExpect(jsonPath("$.sourceName", is("The Post"))); } |
### Question:
ReadingHistoryController { public void addReadPost(Post post) { if (postIsRead(post)) { return; } SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues val = new ContentValues(); val.put(ReadingHistoryContract.HistoryEntry.COLUMN_POST_UUID, post.getUuid()); db.insert(ReadingHistoryContract.HistoryEntry.TABLE_NAME, null, val); db.close(); } private ReadingHistoryController(); static ReadingHistoryController getInstance(); void initialize(Context context); boolean postIsRead(Post post); void addReadPost(Post post); }### Answer:
@Test public void addReadPostTest() throws Exception { ReadingHistoryController.getInstance().initialize(RuntimeEnvironment.application); Post posta = new Post(); posta.setUuid("abc"); Post postb = new Post(); postb.setUuid("123"); ReadingHistoryController.getInstance().addReadPost(posta); assertTrue(ReadingHistoryController.getInstance().postIsRead(posta)); assertFalse(ReadingHistoryController.getInstance().postIsRead(postb)); } |
### Question:
PreferenceJsonController { public Object get(Context context, String key) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE, Context.MODE_PRIVATE); return parser.fromJson(settings.getString(key, ""), Object.class); } PreferenceJsonController(); Object get(Context context, String key); Integer getAsInt(Context context, String key); List<T> getAsList(Context context, String key, TypeToken token); void put(Context context, String key, Object value); }### Answer:
@Test public void get() throws Exception { PreferenceJsonController<SourceSetting> preferences = new PreferenceJsonController<>(); preferences.put(RuntimeEnvironment.application, "abc", 12345); assertEquals(preferences.getAsInt(RuntimeEnvironment.application, "abc"), new Integer(12345)); List<String> collection = new ArrayList<String>(); collection.add("abc"); collection.add("123"); preferences.put(RuntimeEnvironment.application, "123", collection); assertTrue(preferences.getAsList(RuntimeEnvironment.application, "123", new TypeToken<List<String>>(){}) .contains("123")); } |
### Question:
FileRenameBean { public String renameFile(VirtualFile vf) { StringBuilder filename = new StringBuilder(); filename.append(TIMESTAMP.format(vf.getDateTime())); filename.append(SEP).append(vf.getDestination()); filename.append(SEP).append(vf.getOriginator()); filename.append(SEP).append(vf.getDatasetName()); return filename.toString(); } String renameFile(VirtualFile vf); }### Answer:
@Test public void testFileRenameBean() { DefaultVirtualFile dvf = new DefaultVirtualFile(); dvf.setDatasetName("foo"); dvf.setOriginator("bar"); Date time = Calendar.getInstance().getTime(); dvf.setDateTime(time); String name = new FileRenameBean().renameFile(dvf); String string = new String(Long.toString(time.getTime(), 16) + "_bar_foo"); Assert.assertEquals(string, name); } |
### Question:
SecurityUtil { public static PrivateKey getPrivateKey(KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { installBouncyCastleProviderIfNecessary(); PrivateKey key = null; Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String entry = aliases.nextElement(); if (ks.isKeyEntry(entry)) { key = (PrivateKey) ks.getKey(entry, password); break; } } return key; } static KeyStore openKeyStore(File path, char[] password); static PrivateKey getPrivateKey(KeyStore ks, char[] password); static X509Certificate openCertificate(File path); static void installBouncyCastleProviderIfNecessary(); static X509Certificate getCertificateEntry(KeyStore ks); static byte[] computeFileHash(File file, String algorithm); static final String BC_PROVIDER; static final String DEFAULT_OFTP_HASH_ALGORITHM; }### Answer:
@Test public void testGetPrivateKey() throws Exception { File path = OftpTestUtil.getResourceFile(KS_PATH); KeyStore ks = openKeyStore(path, KS_PWD); PrivateKey key = getPrivateKey(ks, KS_PWD); assertNotNull("No private-key were found.", key); } |
### Question:
SecurityUtil { public static byte[] computeFileHash(File file, String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException, IOException { installBouncyCastleProviderIfNecessary(); MessageDigest hash = MessageDigest.getInstance(algorithm, BC_PROVIDER); FileChannel fileChannel = (new FileInputStream(file)).getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(COMPUTING_HASH_BUFFER_SIZE); while (fileChannel.read(buf) != -1) { buf.flip(); hash.update(buf); buf.clear(); } try { fileChannel.close(); } catch (IOException e) { } return hash.digest(); } static KeyStore openKeyStore(File path, char[] password); static PrivateKey getPrivateKey(KeyStore ks, char[] password); static X509Certificate openCertificate(File path); static void installBouncyCastleProviderIfNecessary(); static X509Certificate getCertificateEntry(KeyStore ks); static byte[] computeFileHash(File file, String algorithm); static final String BC_PROVIDER; static final String DEFAULT_OFTP_HASH_ALGORITHM; }### Answer:
@Test public void testComputeFileHash() throws Exception { File data = getResourceFile(TEST_FILE_PATH); byte[] hash = computeFileHash(data, DEFAULT_OFTP_HASH_ALGORITHM); assertNotNull("Failed to compute file hash: " + DEFAULT_OFTP_HASH_ALGORITHM, hash); assertEquals(DEFAULT_OFTP_HASH_ALGORITHM + " : bad digest were produced.", 20, hash.length); } |
### Question:
JSONBeanUtil { public static Properties parsePropertiesFromJSONBean(final String json) throws JSONException { final Properties properties = new Properties(); final JSONObject obj = new JSONObject(json); @SuppressWarnings("unchecked") final Iterator<String> iterator = obj.keys(); while (iterator.hasNext()) { final String key = iterator.next(); final String value = String.valueOf(obj.get(key)); properties.setProperty(key, value); } return properties; } static Properties parsePropertiesFromJSONBean(final String json); static String mapToJSONBean(final Map<String,Object> map); }### Answer:
@Test public void parsePropertiesFromJSONBeanTest() throws JsonProcessingException, JSONException { ObjectMapper mapper = new ObjectMapper(); SimpleInputBean bean = new SimpleInputBean(); bean.setA(20); bean.setB(30); String jsonBean = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean); Properties properties = JSONBeanUtil.parsePropertiesFromJSONBean(jsonBean); Assert.assertTrue(properties.containsKey("a")); Assert.assertEquals("20", properties.get("a")); Assert.assertTrue(properties.containsKey("b")); Assert.assertEquals("30", properties.get("b")); } |
### Question:
JSONBeanUtil { public static String mapToJSONBean(final Map<String,Object> map) { final JSONObject obj = new JSONObject(); for (String key : map.keySet()) { if (! key.startsWith("#")) { obj.put(key, map.get(key)); } } return obj.toString(); } static Properties parsePropertiesFromJSONBean(final String json); static String mapToJSONBean(final Map<String,Object> map); }### Answer:
@Test public void mapToJsonBeanTest() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); SimpleOutputBean bean = new SimpleOutputBean(); bean.setC(50); String jsonBeanExcpected = mapper.writeValueAsString(bean); Map<String,Object> map = new HashMap<>(); map.put("c", 50); map.put("#update-count-1",0); String jsonBeanActual = JSONBeanUtil.mapToJSONBean(map); Assert.assertEquals(jsonBeanExcpected, jsonBeanActual); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer) { mCoachmarkView.setButtonRenderer(renderer); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withButtonRendererTest() throws Exception { ButtonRenderer rendererMock = Mockito.mock(ButtonRenderer.class); mBuilderToTest.withButtonRenderer(rendererMock); verify(mCoachmarkViewMock, times(1)).setButtonRenderer(rendererMock); } |
### Question:
NoAnimationRenderer implements AnimationRenderer { @Override public void animate(final CoachmarkViewLayout layout, final CircleView view, final AnimationListener animationListener) { RectF mCircleRectF = layout.calcCircleRectF(); view.setRadius(mCircleRectF.width() / 2); view.setCenterX(mCircleRectF.centerX()); view.setCenterY(mCircleRectF.centerY()); animationListener.onAnimationFinished(); } @Override void animate(final CoachmarkViewLayout layout, final CircleView view, final AnimationListener animationListener); }### Answer:
@Test public void testAnimate() { CoachmarkViewLayout layoutMock = Mockito.mock(CoachmarkViewLayout.class); AnimationListener animationListenerMock = Mockito.mock(AnimationListener.class); CircleView circleViewMock = Mockito.mock(CircleView.class); RectF rectFMock = Mockito.mock(RectF.class); when(rectFMock.width()).thenReturn(10f); when(rectFMock.centerX()).thenReturn(3f); when(rectFMock.centerY()).thenReturn(3f); when(layoutMock.calcCircleRectF()).thenReturn(rectFMock); new NoAnimationRenderer().animate(layoutMock, circleViewMock, animationListenerMock); verify(layoutMock, times(1)).calcCircleRectF(); verify(circleViewMock).setRadius(5f); verify(circleViewMock).setCenterX(3f); verify(circleViewMock).setCenterY(3f); verify(animationListenerMock, times(1)).onAnimationFinished(); } |
### Question:
TopOfCircleActionDescriptionRenderer implements ActionDescriptionRenderer { @Override public void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow) { RectF circleRectangle = layout.calcCircleRectF(); actionDescription.setX(circleRectangle.centerX() - (actionDescription.getWidth() / 2)); actionDescription.setY(circleRectangle.top - actionArrow.getHeight() - actionDescription.getHeight()); actionArrow.setRotation(90); actionArrow.setX(circleRectangle.centerX() - (actionArrow.getWidth() / 2)); actionArrow.setY(circleRectangle.top - actionArrow.getHeight()); } @Override void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow); @Override boolean isRenderingPossible(CoachmarkViewLayout layout); }### Answer:
@Test public void renderTest() { View actionDescription = Mockito.mock(View.class); View actionArrow = Mockito.mock(View.class); Mockito.when(actionArrow.getWidth()).thenReturn(10); Mockito.when(actionDescription.getWidth()).thenReturn(20); Mockito.when(actionArrow.getHeight()).thenReturn(10); Mockito.when(actionDescription.getHeight()).thenReturn(20); CoachmarkViewLayout layoutMock = Mockito.mock(CoachmarkViewLayout.class); Mockito.when(layoutMock.calcScreenRectF()).thenReturn(new RectF(0, 0, 300, 300)); Mockito.when(layoutMock.calcCircleRectF()).thenReturn(new RectF(50, 50, 75, 75)); new TopOfCircleActionDescriptionRenderer().render(layoutMock, actionDescription, actionArrow); verify(actionDescription, times(1)).setX(52.5f); verify(actionDescription, times(1)).setY(20); verify(actionArrow, times(1)).setX(57.5f); verify(actionArrow, times(1)).setY(40); } |
### Question:
LeftOfCircleActionDescriptionRenderer implements ActionDescriptionRenderer { @Override public void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow) { RectF circleRectangle = layout.calcCircleRectF(); int mWidth = actionDescription.getWidth() + actionArrow.getWidth(); actionDescription.setX((int) (circleRectangle.left - mWidth)); actionDescription.setY(circleRectangle.centerY() - (actionDescription.getHeight() / 2)); actionArrow.setX(circleRectangle.left - actionArrow.getWidth()); actionArrow.setY(circleRectangle.centerY() - (actionArrow.getHeight() / 2)); } @Override void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow); @Override boolean isRenderingPossible(CoachmarkViewLayout layout); }### Answer:
@Test public void renderTest() { View actionDescription = Mockito.mock(View.class); View actionArrow = Mockito.mock(View.class); Mockito.when(actionArrow.getWidth()).thenReturn(30); Mockito.when(actionDescription.getWidth()).thenReturn(15); Mockito.when(actionArrow.getHeight()).thenReturn(10); Mockito.when(actionDescription.getHeight()).thenReturn(20); CoachmarkViewLayout layoutMock = Mockito.mock(CoachmarkViewLayout.class); Mockito.when(layoutMock.calcScreenRectF()).thenReturn(new RectF(0, 0, 300, 95)); Mockito.when(layoutMock.calcCircleRectF()).thenReturn(new RectF(50, 50, 75, 75)); new LeftOfCircleActionDescriptionRenderer().render(layoutMock, actionDescription, actionArrow); verify(actionDescription, times(1)).setX(5); verify(actionDescription, times(1)).setY(52.5f); verify(actionArrow, times(1)).setX(20); verify(actionArrow, times(1)).setY(57.5f); } |
### Question:
BelowCircleActionDescriptionRenderer implements ActionDescriptionRenderer { @Override public void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow) { RectF circleRectangle = layout.calcCircleRectF(); actionDescription.setX(circleRectangle.centerX() - (actionDescription.getWidth() / 2)); actionDescription.setY(circleRectangle.bottom + actionArrow.getHeight()); actionArrow.setRotation(270); actionArrow.setX(circleRectangle.centerX() - (actionArrow.getWidth() / 2)); actionArrow.setY(circleRectangle.bottom); } @Override void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow); @Override boolean isRenderingPossible(CoachmarkViewLayout layout); }### Answer:
@Test public void renderTest() { View actionDescription = Mockito.mock(View.class); View actionArrow = Mockito.mock(View.class); Mockito.when(actionArrow.getWidth()).thenReturn(10); Mockito.when(actionDescription.getWidth()).thenReturn(20); Mockito.when(actionArrow.getHeight()).thenReturn(10); Mockito.when(actionDescription.getHeight()).thenReturn(20); CoachmarkViewLayout layoutMock = Mockito.mock(CoachmarkViewLayout.class); Mockito.when(layoutMock.calcScreenRectF()).thenReturn(new RectF(0, 0, 300, 95)); Mockito.when(layoutMock.calcCircleRectF()).thenReturn(new RectF(50, 50, 75, 75)); new BelowCircleActionDescriptionRenderer().render(layoutMock, actionDescription, actionArrow); verify(actionDescription, times(1)).setX(52.5f); verify(actionDescription, times(1)).setY(85); verify(actionArrow, times(1)).setX(57.5f); verify(actionArrow, times(1)).setY(75); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withBackgroundColor(int color) { mCoachmarkView.setBackColor(color); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withBackgroundColorTest() throws Exception { mBuilderToTest.withBackgroundColor(0); verify(mCoachmarkViewMock, times(1)).setBackColor(0); } |
### Question:
RightOfCircleActionDescriptionRenderer implements ActionDescriptionRenderer { @Override public void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow) { RectF circleRectangle = layout.calcCircleRectF(); actionDescription.setX((int) (circleRectangle.right + actionArrow.getWidth())); actionDescription.setY(circleRectangle.centerY() - (actionDescription.getHeight() / 2)); actionArrow.setRotation(180); actionArrow.setX(circleRectangle.right); actionArrow.setY(circleRectangle.centerY() - (actionArrow.getHeight() / 2)); } @Override void render(CoachmarkViewLayout layout, View actionDescription, View actionArrow); @Override boolean isRenderingPossible(CoachmarkViewLayout layout); }### Answer:
@Test public void renderTest() { View actionDescription = Mockito.mock(View.class); View actionArrow = Mockito.mock(View.class); Mockito.when(actionArrow.getWidth()).thenReturn(30); Mockito.when(actionDescription.getWidth()).thenReturn(15); Mockito.when(actionArrow.getHeight()).thenReturn(10); Mockito.when(actionDescription.getHeight()).thenReturn(20); CoachmarkViewLayout layoutMock = Mockito.mock(CoachmarkViewLayout.class); Mockito.when(layoutMock.calcScreenRectF()).thenReturn(new RectF(0, 0, 300, 95)); Mockito.when(layoutMock.calcCircleRectF()).thenReturn(new RectF(50, 50, 75, 75)); new RightOfCircleActionDescriptionRenderer().render(layoutMock, actionDescription, actionArrow); verify(actionDescription, times(1)).setX(105.0f); verify(actionDescription, times(1)).setY(52.5f); verify(actionArrow, times(1)).setX(75); verify(actionArrow, times(1)).setY(57.5f); } |
### Question:
OkAndCancelAtRightCornerButtonRenderer implements ButtonRenderer { @Override public View render(final CoachmarkViewLayout layout) { mView.setDismissListener(layout); if (mView.getParent() == null) { layout.addView(mView); } return mView; } private OkAndCancelAtRightCornerButtonRenderer(OkAndCancelAtRightCornerButtonRendererView view); @Override View render(final CoachmarkViewLayout layout); }### Answer:
@Test public void renderTest() throws NoSuchFieldException, IllegalAccessException { OkAndCancelAtRightCornerButtonRenderer.Builder mBuilder = new OkAndCancelAtRightCornerButtonRenderer.Builder(Mockito.mock(Context.class)); OkAndCancelAtRightCornerButtonRenderer renderer = mBuilder.build(); OkAndCancelAtRightCornerButtonRendererView viewMock = Mockito.mock(OkAndCancelAtRightCornerButtonRendererView.class); ReflectionUtil.setField(OkAndCancelAtRightCornerButtonRenderer.class, renderer, "mView", viewMock); CoachmarkViewLayout layout = Mockito.mock(CoachmarkViewLayout.class); renderer.render(layout); verify(viewMock, times(1)).setDismissListener(layout); verify(layout, times(1)).addView(viewMock); } |
### Question:
DismissOnTouchNoButtonRenderer implements ButtonRenderer { @Override public View render(final CoachmarkViewLayout layout) { if (inflated == null) { LayoutInflater inflater = (LayoutInflater) layout.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflated = inflater.inflate(R.layout.dismiss_no_button_view, null); layout.addView(inflated); } inflated.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener == null || mListener.onClicked()) { layout.dismiss(); } } }); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); inflated.setLayoutParams(params); inflated.setVisibility(View.VISIBLE); return inflated; } private DismissOnTouchNoButtonRenderer(); @Override View render(final CoachmarkViewLayout layout); }### Answer:
@Test public void renderTest() throws NoSuchFieldException, IllegalAccessException { View mMock = Mockito.mock(View.class); DismissOnTouchNoButtonRenderer renderer = new DismissOnTouchNoButtonRenderer.Builder().build(); ReflectionUtil.setField(DismissOnTouchNoButtonRenderer.class, renderer, "inflated", mMock); renderer.render(null); verify(mMock, times(1)).setOnClickListener(any(View.OnClickListener.class)); verify(mMock).setLayoutParams(any(FrameLayout.LayoutParams.class)); verify(mMock).setVisibility(View.VISIBLE); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers) { mCoachmarkView.setActionDescriptionRenderer(renderers); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withActionDescriptionRenderers() throws Exception { mBuilderToTest.withActionDescriptionRenderers(null); verify(mCoachmarkViewMock, times(1)).setActionDescriptionRenderer(null); } |
### Question:
CoachmarkView extends FrameLayout implements CoachmarkViewLayout, AnimationListener { @Override public boolean isInEditMode() { return true; } CoachmarkView(Context context); CoachmarkView(Context context, AttributeSet attrs); CoachmarkView(Context context, AttributeSet attrs, int defStyleAttr); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) CoachmarkView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes); @Override void onAnimationFinished(); CoachmarkView show(); @NonNull RectF calcActionArrowRect(); RectF calcActionDescriptionRect(); RectF calcDescriptionRect(); RectF calcScreenRectF(); RectF calcCircleRectF(); @Override boolean isInEditMode(); void setActionDescription(View actionDescription); void setDescription(View description); void setActionDescriptionRenderer(ActionDescriptionRenderer... actionDescriptionRenderer); void setDescriptionRenderer(DescriptionRenderer descriptionRenderer); void setView(View view); void setButtonRenderer(ButtonRenderer buttonRenderer); void setBackColor(int backColor); void setPaddingAroundCircle(int paddingAroundCircle); @Override void dismiss(); void setAnimationRenderer(AnimationRenderer animationRenderer); void setDismissListener(DismissListener listener); }### Answer:
@Test public void testIsInEditMode() { Assert.assertTrue(mCoachmarkView.isInEditMode()); } |
### Question:
CoachmarkView extends FrameLayout implements CoachmarkViewLayout, AnimationListener { @Override public void dismiss() { mWindowManager.removeView(CoachmarkView.this); if (mDismissListener != null) { mDismissListener.onDismiss(); } } CoachmarkView(Context context); CoachmarkView(Context context, AttributeSet attrs); CoachmarkView(Context context, AttributeSet attrs, int defStyleAttr); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) CoachmarkView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes); @Override void onAnimationFinished(); CoachmarkView show(); @NonNull RectF calcActionArrowRect(); RectF calcActionDescriptionRect(); RectF calcDescriptionRect(); RectF calcScreenRectF(); RectF calcCircleRectF(); @Override boolean isInEditMode(); void setActionDescription(View actionDescription); void setDescription(View description); void setActionDescriptionRenderer(ActionDescriptionRenderer... actionDescriptionRenderer); void setDescriptionRenderer(DescriptionRenderer descriptionRenderer); void setView(View view); void setButtonRenderer(ButtonRenderer buttonRenderer); void setBackColor(int backColor); void setPaddingAroundCircle(int paddingAroundCircle); @Override void dismiss(); void setAnimationRenderer(AnimationRenderer animationRenderer); void setDismissListener(DismissListener listener); }### Answer:
@Test public void testIsCoachmarkDismissed() { mCoachmarkView.dismiss(); Assert.assertTrue(mCoachmarkView.getWindowToken() == null); } |
### Question:
CoachmarkView extends FrameLayout implements CoachmarkViewLayout, AnimationListener { public RectF calcScreenRectF() { return new RectF(0, 0, getWidth(), getHeight()); } CoachmarkView(Context context); CoachmarkView(Context context, AttributeSet attrs); CoachmarkView(Context context, AttributeSet attrs, int defStyleAttr); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) CoachmarkView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes); @Override void onAnimationFinished(); CoachmarkView show(); @NonNull RectF calcActionArrowRect(); RectF calcActionDescriptionRect(); RectF calcDescriptionRect(); RectF calcScreenRectF(); RectF calcCircleRectF(); @Override boolean isInEditMode(); void setActionDescription(View actionDescription); void setDescription(View description); void setActionDescriptionRenderer(ActionDescriptionRenderer... actionDescriptionRenderer); void setDescriptionRenderer(DescriptionRenderer descriptionRenderer); void setView(View view); void setButtonRenderer(ButtonRenderer buttonRenderer); void setBackColor(int backColor); void setPaddingAroundCircle(int paddingAroundCircle); @Override void dismiss(); void setAnimationRenderer(AnimationRenderer animationRenderer); void setDismissListener(DismissListener listener); }### Answer:
@Test public void testCalcScreenRectF() { mActivity.addContentView(mCoachmarkView, new LinearLayout.LayoutParams(200, 200)); RectF mRectF = mCoachmarkView.calcScreenRectF(); Assert.assertEquals(200.0f, mRectF.width()); Assert.assertEquals(200.0f, mRectF.height()); Assert.assertEquals(0.0f, mRectF.left); Assert.assertEquals(0.0f, mRectF.top); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer) { mCoachmarkView.setDescriptionRenderer(renderer); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withDescriptionRenderer() throws Exception { mBuilderToTest.withDescriptionRenderer(null); verify(mCoachmarkViewMock, times(1)).setDescriptionRenderer(null); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withActionDescription(View actionDescription) { mCoachmarkView.setActionDescription(actionDescription); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withActionDescriptionTest() throws Exception { mBuilderToTest.withActionDescription(null); verify(mCoachmarkViewMock, times(1)).setActionDescription(null); } |
### Question:
CoachmarkViewBuilder { public CoachmarkView buildAroundView(View view) { mCoachmarkView.setView(view); return mCoachmarkView; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void buildAroundViewTest() { View mMock = Mockito.mock(View.class); mBuilderToTest.buildAroundView(mMock); verify(mCoachmarkViewMock, times(1)).setView(mMock); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withDescription(View description) { mCoachmarkView.setDescription(description); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withDescriptionTest() throws Exception { mBuilderToTest.withDescription(null); verify(mCoachmarkViewMock, times(1)).setDescription(null); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withPaddingAroundCircle(int padding) { mCoachmarkView.setPaddingAroundCircle(padding); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withPaddingAroundCircle() throws Exception { mBuilderToTest.withPaddingAroundCircle(2); verify(mCoachmarkViewMock, times(1)).setPaddingAroundCircle(2); } |
### Question:
CoachmarkViewBuilder { public CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer){ mCoachmarkView.setAnimationRenderer(renderer); return this; } CoachmarkViewBuilder(Context context); CoachmarkViewBuilder withButtonRenderer(ButtonRenderer renderer); CoachmarkView buildAroundView(View view); CoachmarkView build(); CoachmarkViewBuilder withBackgroundColor(int color); CoachmarkViewBuilder withActionDescriptionRenderers(ActionDescriptionRenderer... renderers); CoachmarkViewBuilder withDescriptionRenderer(DescriptionRenderer renderer); CoachmarkViewBuilder withActionDescription(View actionDescription); CoachmarkViewBuilder withDescription(View description); CoachmarkViewBuilder withPaddingAroundCircle(int padding); CoachmarkViewBuilder withCircleColor(int color); CoachmarkViewBuilder withAnimationRenderer(AnimationRenderer renderer); }### Answer:
@Test public void withAnimationRenderer() throws Exception { AnimationRenderer mMock = Mockito.mock(AnimationRenderer.class); mBuilderToTest.withAnimationRenderer(mMock); verify(mCoachmarkViewMock, times(1)).setAnimationRenderer(mMock); } |
### Question:
CircleView extends View { @Override protected void dispatchDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(defaultColor); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); canvas.drawCircle(mCenterX, mCenterY, mRadius, paint); if(mTransparentRadius != 0){ Paint paintTransparent = new Paint(); paintTransparent.setColor(Color.YELLOW); paintTransparent.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); canvas.drawCircle(mCenterX, mCenterY, mTransparentRadius, paintTransparent); } super.dispatchDraw(canvas); } CircleView(Context context); CircleView(Context context, AttributeSet attrs); CircleView(Context context, AttributeSet attrs, int defStyleAttr); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) CircleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes); void setCenterX(float mCenterX); void setCenterY(float mCenterY); void setRadius(float radius); void setColor(int color); void setTransparentRadius(float radius); }### Answer:
@Test public void testDispatchDraw() { ActivityController<Activity> activityController = Robolectric.buildActivity(Activity.class).create().start().resume() .visible(); Activity activity = activityController.get(); CircleView mView = new CircleView(activity); mView.setCenterY(2); mView.setCenterX(3); mView.setRadius(22); Canvas canvasMock = Mockito.mock(Canvas.class); mView.dispatchDraw(canvasMock); verify(canvasMock).drawCircle(Matchers.eq(3.0f), Matchers.eq(2.0f), Matchers.eq(22.0f), any(Paint.class)); } |
### Question:
PageDataExtractorOverTimeGui extends AbstractOverTimeVisualizer implements CMDLineArgumentsProcessor { @Override protected JSettingsPanel createSettingsPanel() { return new JSettingsPanel(this, JSettingsPanel.GRADIENT_OPTION | JSettingsPanel.MAXY_OPTION | JSettingsPanel.RELATIVE_TIME_OPTION | JSettingsPanel.AUTO_EXPAND_OPTION | JSettingsPanel.MARKERS_OPTION); } PageDataExtractorOverTimeGui(); @Override String getStaticLabel(); @Override String getLabelResource(); @Override String getWikiPage(); @Override TestElement createTestElement(); @Override void modifyTestElement(TestElement te); @Override void configure(TestElement te); @Override void add(SampleResult res); @Override void clearData(); void processCMDOption(String nextArg, ListIterator args); static final String[] columnIdentifiers; static final Class[] columnClasses; }### Answer:
@Test public void testCreateSettingsPanel() { System.out.println("createSettingsPanel"); PageDataExtractorOverTimeGui instance = new PageDataExtractorOverTimeGui(); JSettingsPanel result = instance.createSettingsPanel(); assertNotNull(result); } |
### Question:
ConsoleStatusLogger extends AbstractListenerElement implements SampleListener, Serializable,
NoThreadClone, TestStateListener { @Override public synchronized void sampleOccurred(SampleEvent se) { long sec = System.currentTimeMillis() / 1000; if (sec != cur && count > 0) { if (cur == 0) { begin = sec; } log.debug(cur + " " + begin); flush(sec - begin); cur = sec; } SampleResult res = se.getResult(); count++; sumRTime += res.getTime(); sumLatency += res.getLatency(); errors += res.isSuccessful() ? 0 : 1; threads = res.getAllThreads(); } @Override synchronized void sampleOccurred(SampleEvent se); @Override void sampleStarted(SampleEvent se); @Override void sampleStopped(SampleEvent se); @Override void testStarted(); @Override void testStarted(String string); @Override void testEnded(); @Override void testEnded(String string); }### Answer:
@Test public void testSampleOccurred() throws InterruptedException { System.out.println("sampleOccurred"); SampleResult res = new SampleResult(); res.setResponseCode("200"); SampleEvent se = new SampleEvent(res, "testTG"); ConsoleStatusLogger instance = new ConsoleStatusLogger(); instance.testStarted(); instance.sampleOccurred(se); instance.sampleOccurred(se); Thread.sleep(1020); instance.sampleOccurred(se); instance.sampleOccurred(se); Thread.sleep(1020); instance.sampleOccurred(se); instance.sampleOccurred(se); } |
### Question:
ConsoleStatusLogger extends AbstractListenerElement implements SampleListener, Serializable,
NoThreadClone, TestStateListener { @Override public void sampleStarted(SampleEvent se) { } @Override synchronized void sampleOccurred(SampleEvent se); @Override void sampleStarted(SampleEvent se); @Override void sampleStopped(SampleEvent se); @Override void testStarted(); @Override void testStarted(String string); @Override void testEnded(); @Override void testEnded(String string); }### Answer:
@Test public void testSampleStarted() { System.out.println("sampleStarted"); SampleEvent se = null; ConsoleStatusLogger instance = new ConsoleStatusLogger(); instance.sampleStarted(se); } |
### Question:
ConsoleStatusLogger extends AbstractListenerElement implements SampleListener, Serializable,
NoThreadClone, TestStateListener { @Override public void sampleStopped(SampleEvent se) { } @Override synchronized void sampleOccurred(SampleEvent se); @Override void sampleStarted(SampleEvent se); @Override void sampleStopped(SampleEvent se); @Override void testStarted(); @Override void testStarted(String string); @Override void testEnded(); @Override void testEnded(String string); }### Answer:
@Test public void testSampleStopped() { System.out.println("sampleStopped"); SampleEvent se = null; ConsoleStatusLogger instance = new ConsoleStatusLogger(); instance.sampleStopped(se); } |
### Question:
ConsoleStatusLogger extends AbstractListenerElement implements SampleListener, Serializable,
NoThreadClone, TestStateListener { @Override public void testStarted() { if (JMeter.isNonGUI()) { out = System.out; } else { out = new JMeterLoggerOutputStream(log); } cur = 0; } @Override synchronized void sampleOccurred(SampleEvent se); @Override void sampleStarted(SampleEvent se); @Override void sampleStopped(SampleEvent se); @Override void testStarted(); @Override void testStarted(String string); @Override void testEnded(); @Override void testEnded(String string); }### Answer:
@Test public void testTestStarted_0args() { System.out.println("testStarted"); ConsoleStatusLogger instance = new ConsoleStatusLogger(); instance.testStarted(); }
@Test public void testTestStarted_String() { System.out.println("testStarted"); String string = ""; ConsoleStatusLogger instance = new ConsoleStatusLogger(); instance.testStarted(string); } |
### Question:
ConsoleStatusLogger extends AbstractListenerElement implements SampleListener, Serializable,
NoThreadClone, TestStateListener { @Override public void testEnded() { } @Override synchronized void sampleOccurred(SampleEvent se); @Override void sampleStarted(SampleEvent se); @Override void sampleStopped(SampleEvent se); @Override void testStarted(); @Override void testStarted(String string); @Override void testEnded(); @Override void testEnded(String string); }### Answer:
@Test public void testTestEnded_0args() { System.out.println("testEnded"); ConsoleStatusLogger instance = new ConsoleStatusLogger(); instance.testEnded(); }
@Test public void testTestEnded_String() { System.out.println("testEnded"); String string = ""; ConsoleStatusLogger instance = new ConsoleStatusLogger(); instance.testEnded(string); } |
### Question:
ConsoleStatusLoggerGui extends AbstractListenerGui { @Override public String getStaticLabel() { return JMeterPluginsUtils.prefixLabel("Console Status Logger"); } ConsoleStatusLoggerGui(); @Override String getStaticLabel(); @Override String getLabelResource(); @Override TestElement createTestElement(); @Override void modifyTestElement(TestElement te); static final String WIKIPAGE; }### Answer:
@Test public void testGetStaticLabel() { System.out.println("getStaticLabel"); ConsoleStatusLoggerGui instance = new ConsoleStatusLoggerGui(); String result = instance.getStaticLabel(); assertTrue(result.length() > 0); } |
### Question:
ConsoleStatusLoggerGui extends AbstractListenerGui { @Override public String getLabelResource() { return getClass().getCanonicalName(); } ConsoleStatusLoggerGui(); @Override String getStaticLabel(); @Override String getLabelResource(); @Override TestElement createTestElement(); @Override void modifyTestElement(TestElement te); static final String WIKIPAGE; }### Answer:
@Test public void testGetLabelResource() { System.out.println("getLabelResource"); ConsoleStatusLoggerGui instance = new ConsoleStatusLoggerGui(); String result = instance.getLabelResource(); assertTrue(result.length() > 0); } |
### Question:
ConsoleStatusLoggerGui extends AbstractListenerGui { @Override public TestElement createTestElement() { TestElement te = new ConsoleStatusLogger(); modifyTestElement(te); te.setComment(JMeterPluginsUtils.getWikiLinkText(WIKIPAGE)); return te; } ConsoleStatusLoggerGui(); @Override String getStaticLabel(); @Override String getLabelResource(); @Override TestElement createTestElement(); @Override void modifyTestElement(TestElement te); static final String WIKIPAGE; }### Answer:
@Test public void testCreateTestElement() { System.out.println("createTestElement"); ConsoleStatusLoggerGui instance = new ConsoleStatusLoggerGui(); TestElement result = instance.createTestElement(); assertTrue(result instanceof ConsoleStatusLogger); } |
### Question:
ConsoleStatusLoggerGui extends AbstractListenerGui { @Override public void modifyTestElement(TestElement te) { super.configureTestElement(te); } ConsoleStatusLoggerGui(); @Override String getStaticLabel(); @Override String getLabelResource(); @Override TestElement createTestElement(); @Override void modifyTestElement(TestElement te); static final String WIKIPAGE; }### Answer:
@Test public void testModifyTestElement() { System.out.println("modifyTestElement"); TestElement te = new ConsoleStatusLogger(); ConsoleStatusLoggerGui instance = new ConsoleStatusLoggerGui(); instance.modifyTestElement(te); } |
### Question:
VariablesFromCSV extends Arguments { @Override public Map<String, String> getArgumentsAsMap() { Map<String, String> variables = new VariableFromCsvFileReader(getFileName()).getDataAsMap(getVariablePrefix(), getSeparator(), getSkipLines()); if (isStoreAsSystemProperty()) { for (Map.Entry<String, String> element : variables.entrySet()) { String variable = element.getKey(); if (System.getProperty(variable) == null) { System.setProperty(variable, element.getValue()); } } } return variables; } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testGetArgumentsAsMap() { System.out.println("getArgumentsAsMap"); VariablesFromCSV instance = new VariablesFromCSV(); instance.setFileName(fileName); instance.setSeparator(","); Map result = instance.getArgumentsAsMap(); assertEquals(result.size(), 2); } |
### Question:
VariablesFromCSV extends Arguments { public String getVariablePrefix() { return getPropertyAsString(VARIABLE_PREFIX); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testGetVariablePrefix() { System.out.println("getVariablePrefix"); VariablesFromCSV instance = new VariablesFromCSV(); String expResult = ""; String result = instance.getVariablePrefix(); assertEquals(expResult, result); } |
### Question:
VariablesFromCSV extends Arguments { public void setVariablePrefix(String prefix) { setProperty(VARIABLE_PREFIX, prefix); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testSetVariablePrefix() { System.out.println("setVariablePrefix"); String prefix = ""; VariablesFromCSV instance = new VariablesFromCSV(); instance.setVariablePrefix(prefix); } |
### Question:
VariablesFromCSV extends Arguments { public String getFileName() { return getPropertyAsString(FILENAME); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testGetFileName() { System.out.println("getFileName"); VariablesFromCSV instance = new VariablesFromCSV(); String expResult = ""; String result = instance.getFileName(); assertEquals(expResult, result); } |
### Question:
VariablesFromCSV extends Arguments { public void setFileName(String filename) { setProperty(FILENAME, filename); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testSetFileName() { System.out.println("setFileName"); String filename = ""; VariablesFromCSV instance = new VariablesFromCSV(); instance.setFileName(filename); } |
### Question:
VariablesFromCSV extends Arguments { public String getSeparator() { return getPropertyAsString(SEPARATOR); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testGetSeparator() { System.out.println("getSeparator"); VariablesFromCSV instance = new VariablesFromCSV(); String expResult = ""; String result = instance.getSeparator(); assertEquals(expResult, result); } |
### Question:
VariablesFromCSV extends Arguments { public void setSeparator(String separator) { setProperty(SEPARATOR, separator); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testSetSeparator() { System.out.println("setSeparator"); String separator = ""; VariablesFromCSV instance = new VariablesFromCSV(); instance.setSeparator(separator); } |
### Question:
VariablesFromCSV extends Arguments { public boolean isStoreAsSystemProperty() { return getPropertyAsBoolean(STORE_SYS_PROP); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testIsStoreAsSystemProperty() { System.out.println("isStoreAsSystemProperty"); VariablesFromCSV instance = new VariablesFromCSV(); boolean expResult = false; boolean result = instance.isStoreAsSystemProperty(); assertEquals(expResult, result); } |
### Question:
VariablesFromCSV extends Arguments { public void setStoreAsSystemProperty(boolean storeAsSysProp) { setProperty(STORE_SYS_PROP, storeAsSysProp); } @Override Map<String, String> getArgumentsAsMap(); String getVariablePrefix(); void setVariablePrefix(String prefix); String getFileName(); void setFileName(String filename); String getSeparator(); void setSeparator(String separator); int getSkipLines(); void setSkipLines(int skipLines); boolean isStoreAsSystemProperty(); void setStoreAsSystemProperty(boolean storeAsSysProp); static final String VARIABLE_PREFIX; static final String FILENAME; static final String SEPARATOR; static final String SKIP_LINES; static final int SKIP_LINES_DEFAULT; static final String STORE_SYS_PROP; }### Answer:
@Test public void testSetStoreAsSystemProperty() { System.out.println("setStoreAsSystemProperty"); boolean storeAsSysProp = false; VariablesFromCSV instance = new VariablesFromCSV(); instance.setStoreAsSystemProperty(storeAsSysProp); } |
### Question:
MergeResultsGui extends AbstractGraphPanelVisualizer implements
TableModelListener, CellEditorListener, ChangeListener, ActionListener { public String getWikiPage() { return "MergeResults"; } MergeResultsGui(); @Override String getLabelResource(); @Override String getStaticLabel(); @Override Collection<String> getMenuCategories(); void setFile(String filename); String getFile(); String getWikiPage(); JTable getGrid(); @Override void modifyTestElement(TestElement c); @Override void configure(TestElement el); @Override void updateUI(); @Override void add(SampleResult res); @Override void setUpFiltering(CorrectedResultCollector rc); void actionPerformed(ActionEvent action); void checkDeleteButtonStatus(); void checkMergeButtonStatus(); void tableChanged(TableModelEvent e); void editingStopped(ChangeEvent e); void editingCanceled(ChangeEvent e); @Override void stateChanged(ChangeEvent e); @Override Dimension getPreferredSize(); @Override void clearGui(); @Override GraphPanelChart getGraphPanelChart(); static final String WIKIPAGE; static final String[] columnIdentifiers; static final Class<?>[] columnClasses; static final Object[] defaultValues; static final String DEFAULT_FILENAME; static final String FILENAME; static final String DATA_PROPERTY; static final int INPUT_FILE_NAME; static final int PREFIX_LABEL; static final int OFFSET_START; static final int OFFSET_END; static final int INCLUDE_LABEL; static final int REGEX_INCLUDE; static final int EXCLUDE_LABEL; static final int REGEX_EXCLUDE; }### Answer:
@Test public void testGetWikiPage() { System.out.println("getWikiPage"); MergeResultsGui instance = new MergeResultsGui(); String expResult = "MergeResults"; String result = instance.getWikiPage(); assertEquals(expResult, result); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.